ghh1125 commited on
Commit
6e62f14
·
verified ·
1 Parent(s): 69d3086

Upload 256 files

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Dockerfile +18 -0
  2. app.py +45 -0
  3. mpmath/.DS_Store +0 -0
  4. mpmath/mcp_output/README_MCP.md +120 -0
  5. mpmath/mcp_output/analysis.json +720 -0
  6. mpmath/mcp_output/diff_report.md +161 -0
  7. mpmath/mcp_output/mcp_plugin/__init__.py +0 -0
  8. mpmath/mcp_output/mcp_plugin/adapter.py +325 -0
  9. mpmath/mcp_output/mcp_plugin/main.py +13 -0
  10. mpmath/mcp_output/mcp_plugin/mcp_service.py +242 -0
  11. mpmath/mcp_output/requirements.txt +4 -0
  12. mpmath/mcp_output/start_mcp.py +30 -0
  13. mpmath/mcp_output/workflow_summary.json +237 -0
  14. mpmath/source/.DS_Store +0 -0
  15. mpmath/source/.codecov.yml +11 -0
  16. mpmath/source/.readthedocs.yaml +20 -0
  17. mpmath/source/CHANGES +1257 -0
  18. mpmath/source/CITATION.bib +7 -0
  19. mpmath/source/LICENSE +27 -0
  20. mpmath/source/README.rst +188 -0
  21. mpmath/source/__init__.py +4 -0
  22. mpmath/source/conftest.py +26 -0
  23. mpmath/source/demo/mandelbrot.py +33 -0
  24. mpmath/source/demo/manydigits.py +104 -0
  25. mpmath/source/demo/pidigits.py +80 -0
  26. mpmath/source/demo/plotting.py +35 -0
  27. mpmath/source/demo/sofa.py +63 -0
  28. mpmath/source/demo/taylor.py +71 -0
  29. mpmath/source/docs/basics.rst +253 -0
  30. mpmath/source/docs/calculus/approximation.rst +23 -0
  31. mpmath/source/docs/calculus/differentiation.rst +19 -0
  32. mpmath/source/docs/calculus/index.rst +14 -0
  33. mpmath/source/docs/calculus/integration.rst +36 -0
  34. mpmath/source/docs/calculus/inverselaplace.rst +71 -0
  35. mpmath/source/docs/calculus/odes.rst +7 -0
  36. mpmath/source/docs/calculus/optimization.rst +23 -0
  37. mpmath/source/docs/calculus/polynomials.rst +15 -0
  38. mpmath/source/docs/calculus/sums_limits.rst +67 -0
  39. mpmath/source/docs/cli.rst +8 -0
  40. mpmath/source/docs/conf.py +52 -0
  41. mpmath/source/docs/contexts.rst +370 -0
  42. mpmath/source/docs/functions/bessel.rst +106 -0
  43. mpmath/source/docs/functions/constants.rst +45 -0
  44. mpmath/source/docs/functions/elliptic.rst +53 -0
  45. mpmath/source/docs/functions/expintegrals.rst +70 -0
  46. mpmath/source/docs/functions/gamma.rst +79 -0
  47. mpmath/source/docs/functions/hyperbolic.rst +23 -0
  48. mpmath/source/docs/functions/hypergeometric.rst +74 -0
  49. mpmath/source/docs/functions/index.rst +22 -0
  50. mpmath/source/docs/functions/numtheory.rst +58 -0
Dockerfile ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.10
2
+
3
+ RUN useradd -m -u 1000 user && python -m pip install --upgrade pip
4
+ USER user
5
+ ENV PATH="/home/user/.local/bin:$PATH"
6
+
7
+ WORKDIR /app
8
+
9
+ COPY --chown=user ./requirements.txt requirements.txt
10
+ RUN pip install --no-cache-dir --upgrade -r requirements.txt
11
+
12
+ COPY --chown=user . /app
13
+ ENV MCP_TRANSPORT=http
14
+ ENV MCP_PORT=7860
15
+
16
+ EXPOSE 7860
17
+
18
+ CMD ["python", "mpmath/mcp_output/start_mcp.py"]
app.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI
2
+ import os
3
+ import sys
4
+
5
+ mcp_plugin_path = os.path.join(os.path.dirname(__file__), "mpmath", "mcp_output", "mcp_plugin")
6
+ sys.path.insert(0, mcp_plugin_path)
7
+
8
+ app = FastAPI(
9
+ title="Mpmath MCP Service",
10
+ description="Auto-generated MCP service for mpmath",
11
+ version="1.0.0"
12
+ )
13
+
14
+ @app.get("/")
15
+ def root():
16
+ return {
17
+ "service": "Mpmath MCP Service",
18
+ "version": "1.0.0",
19
+ "status": "running",
20
+ "transport": os.environ.get("MCP_TRANSPORT", "http")
21
+ }
22
+
23
+ @app.get("/health")
24
+ def health_check():
25
+ return {"status": "healthy", "service": "mpmath MCP"}
26
+
27
+ @app.get("/tools")
28
+ def list_tools():
29
+ try:
30
+ from mcp_service import create_app
31
+ mcp_app = create_app()
32
+ tools = []
33
+ for tool_name, tool_func in mcp_app.tools.items():
34
+ tools.append({
35
+ "name": tool_name,
36
+ "description": tool_func.__doc__ or "No description available"
37
+ })
38
+ return {"tools": tools}
39
+ except Exception as e:
40
+ return {"error": f"Failed to load tools: {str(e)}"}
41
+
42
+ if __name__ == "__main__":
43
+ import uvicorn
44
+ port = int(os.environ.get("PORT", 7860))
45
+ uvicorn.run(app, host="0.0.0.0", port=port)
mpmath/.DS_Store ADDED
Binary file (6.15 kB). View file
 
mpmath/mcp_output/README_MCP.md ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # mpmath MCP (Model Context Protocol) Service README
2
+
3
+ ## 1) Project Introduction
4
+
5
+ This MCP (Model Context Protocol) service wraps the `mpmath` library to provide high-precision numerical computation for LLM/tool workflows.
6
+
7
+ It is designed for:
8
+ - Arbitrary-precision real/complex arithmetic
9
+ - Numerical calculus (integration, differentiation, root finding)
10
+ - Special functions (zeta, Bessel, elliptic, etc.)
11
+ - Matrix and linear algebra operations
12
+ - Optional interval arithmetic for enclosure-safe results
13
+
14
+ Repository: https://github.com/fredrik-johansson/mpmath
15
+
16
+ ---
17
+
18
+ ## 2) Installation Method
19
+
20
+ ### Requirements
21
+ - Python `>=3.8`
22
+ - Required: `mpmath`
23
+ - Optional:
24
+ - `gmpy2` (faster big-number backend in some workloads)
25
+ - `matplotlib` (plotting/visualization scenarios)
26
+
27
+ ### Install
28
+ pip install mpmath
29
+
30
+ Optional extras:
31
+ pip install gmpy2 matplotlib
32
+
33
+ ---
34
+
35
+ ## 3) Quick Start
36
+
37
+ ### Basic usage
38
+ import mpmath as mp
39
+ mp.mp.dps = 50
40
+ print(mp.sqrt(2))
41
+ print(mp.zeta(3))
42
+ print(mp.quad(lambda x: mp.sin(x), [0, mp.pi]))
43
+
44
+ ### Root finding
45
+ import mpmath as mp
46
+ f = lambda x: mp.cos(x) - x
47
+ root = mp.findroot(f, 0.7)
48
+ print(root)
49
+
50
+ ### Matrix / linear algebra
51
+ import mpmath as mp
52
+ A = mp.matrix([[1, 2], [3, 4]])
53
+ print(A**-1)
54
+ print(mp.det(A))
55
+
56
+ ### CLI mode
57
+ python -m mpmath
58
+
59
+ ---
60
+
61
+ ## 4) Available Tools and Endpoints List
62
+
63
+ Recommended MCP (Model Context Protocol) service endpoints (developer-oriented mapping to `mpmath` APIs):
64
+
65
+ - `set_precision(dps)`
66
+ Set decimal precision (`mp.mp.dps`) for subsequent computations.
67
+
68
+ - `evaluate(expression, dps?)`
69
+ Evaluate a safe mathematical expression with high precision.
70
+
71
+ - `compute_function(name, args, dps?)`
72
+ Call elementary/special functions such as `sqrt`, `exp`, `log`, `sin`, `cos`, `zeta`, etc.
73
+
74
+ - `integrate(function_expr, interval, method?)`
75
+ Numerical integration via `quad`/related quadrature routines.
76
+
77
+ - `differentiate(function_expr, x, order?)`
78
+ Differentiation using `diff` and related helpers.
79
+
80
+ - `find_root(function_expr, x0, x1?)`
81
+ Root solving via `findroot`.
82
+
83
+ - `linear_algebra(operation, matrix, extra?)`
84
+ Operations like `det`, `inverse`, `lu`, `qr`, `svd`, `cond`.
85
+
86
+ - `interval_compute(name, args, dps?)`
87
+ Interval arithmetic via `iv` context (`mpi`, interval-safe transforms).
88
+
89
+ - `constants(name, dps?)`
90
+ Return constants (`pi`, `e`, etc.) at configured precision.
91
+
92
+ Notes:
93
+ - Prefer stateless endpoint design: precision passed per request when possible.
94
+ - Validate expression inputs carefully (avoid arbitrary code execution).
95
+
96
+ ---
97
+
98
+ ## 5) Common Issues and Notes
99
+
100
+ - Precision vs performance: higher `dps` increases CPU/memory cost.
101
+ - Convergence sensitivity: `findroot`, oscillatory integrals, and special functions may require better initial guesses or tuned precision.
102
+ - Numerical stability: consider interval arithmetic (`iv`) for rigorous bounds.
103
+ - Backend differences: availability of `gmpy2` can affect speed and behavior.
104
+ - Serialization: return numeric outputs as strings for very high precision to avoid float truncation.
105
+ - Security: never directly `eval` untrusted expressions without strict parsing/sandboxing.
106
+
107
+ ---
108
+
109
+ ## 6) Reference Links / Documentation
110
+
111
+ - Main repository: https://github.com/fredrik-johansson/mpmath
112
+ - Package docs/source tree (in repo): `docs/`, `mpmath/function_docs.py`
113
+ - CLI entry: `python -m mpmath`
114
+ - Core modules of interest:
115
+ - `mpmath.ctx_mp` (arbitrary precision context)
116
+ - `mpmath.calculus.quadrature` (integration)
117
+ - `mpmath.calculus.optimization` (root finding)
118
+ - `mpmath.calculus.differentiation` (derivatives/Taylor)
119
+ - `mpmath.matrices.linalg` (linear algebra)
120
+ - `mpmath.functions.*` (special functions)
mpmath/mcp_output/analysis.json ADDED
@@ -0,0 +1,720 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "summary": {
3
+ "repository_url": "https://github.com/fredrik-johansson/mpmath",
4
+ "summary": "Imported via zip fallback, file count: 155",
5
+ "file_tree": {
6
+ ".codecov.yml": {
7
+ "size": 159
8
+ },
9
+ ".github/dependabot.yml": {
10
+ "size": 215
11
+ },
12
+ ".github/workflows/coverage.yml": {
13
+ "size": 1489
14
+ },
15
+ ".github/workflows/docs.yml": {
16
+ "size": 1105
17
+ },
18
+ ".github/workflows/linter.yml": {
19
+ "size": 414
20
+ },
21
+ ".github/workflows/publish.yml": {
22
+ "size": 885
23
+ },
24
+ ".github/workflows/test.yml": {
25
+ "size": 1606
26
+ },
27
+ ".readthedocs.yaml": {
28
+ "size": 350
29
+ },
30
+ "conftest.py": {
31
+ "size": 647
32
+ },
33
+ "demo/mandelbrot.py": {
34
+ "size": 699
35
+ },
36
+ "demo/manydigits.py": {
37
+ "size": 2442
38
+ },
39
+ "demo/pidigits.py": {
40
+ "size": 2415
41
+ },
42
+ "demo/plotting.py": {
43
+ "size": 885
44
+ },
45
+ "demo/sofa.py": {
46
+ "size": 1824
47
+ },
48
+ "demo/taylor.py": {
49
+ "size": 2008
50
+ },
51
+ "docs/conf.py": {
52
+ "size": 1717
53
+ },
54
+ "docs/plots/ai.py": {
55
+ "size": 199
56
+ },
57
+ "docs/plots/ai_c.py": {
58
+ "size": 87
59
+ },
60
+ "docs/plots/ber.py": {
61
+ "size": 200
62
+ },
63
+ "docs/plots/besseli.py": {
64
+ "size": 209
65
+ },
66
+ "docs/plots/besseli_c.py": {
67
+ "size": 115
68
+ },
69
+ "docs/plots/besselj.py": {
70
+ "size": 195
71
+ },
72
+ "docs/plots/besselj_c.py": {
73
+ "size": 106
74
+ },
75
+ "docs/plots/besselk.py": {
76
+ "size": 221
77
+ },
78
+ "docs/plots/besselk_c.py": {
79
+ "size": 127
80
+ },
81
+ "docs/plots/bessely.py": {
82
+ "size": 214
83
+ },
84
+ "docs/plots/bessely_c.py": {
85
+ "size": 118
86
+ },
87
+ "docs/plots/bi.py": {
88
+ "size": 207
89
+ },
90
+ "docs/plots/bi_c.py": {
91
+ "size": 87
92
+ },
93
+ "docs/plots/buildplots.py": {
94
+ "size": 701
95
+ },
96
+ "docs/plots/chebyt.py": {
97
+ "size": 222
98
+ },
99
+ "docs/plots/chebyu.py": {
100
+ "size": 222
101
+ },
102
+ "docs/plots/coulombf.py": {
103
+ "size": 270
104
+ },
105
+ "docs/plots/coulombf_c.py": {
106
+ "size": 100
107
+ },
108
+ "docs/plots/coulombg.py": {
109
+ "size": 268
110
+ },
111
+ "docs/plots/coulombg_c.py": {
112
+ "size": 102
113
+ },
114
+ "docs/plots/ellipe.py": {
115
+ "size": 223
116
+ },
117
+ "docs/plots/ellipf.py": {
118
+ "size": 227
119
+ },
120
+ "docs/plots/ellipk.py": {
121
+ "size": 94
122
+ },
123
+ "docs/plots/ellippi.py": {
124
+ "size": 262
125
+ },
126
+ "docs/plots/gi.py": {
127
+ "size": 97
128
+ },
129
+ "docs/plots/gi_c.py": {
130
+ "size": 91
131
+ },
132
+ "docs/plots/hankel1.py": {
133
+ "size": 202
134
+ },
135
+ "docs/plots/hankel1_c.py": {
136
+ "size": 107
137
+ },
138
+ "docs/plots/hankel2.py": {
139
+ "size": 202
140
+ },
141
+ "docs/plots/hankel2_c.py": {
142
+ "size": 107
143
+ },
144
+ "docs/plots/hermite.py": {
145
+ "size": 241
146
+ },
147
+ "docs/plots/hi.py": {
148
+ "size": 103
149
+ },
150
+ "docs/plots/hi_c.py": {
151
+ "size": 91
152
+ },
153
+ "docs/plots/ker.py": {
154
+ "size": 197
155
+ },
156
+ "docs/plots/kleinj.py": {
157
+ "size": 128
158
+ },
159
+ "docs/plots/kleinj2.py": {
160
+ "size": 124
161
+ },
162
+ "docs/plots/laguerre.py": {
163
+ "size": 256
164
+ },
165
+ "docs/plots/lambertw.py": {
166
+ "size": 118
167
+ },
168
+ "docs/plots/lambertw_c.py": {
169
+ "size": 96
170
+ },
171
+ "docs/plots/legendre.py": {
172
+ "size": 231
173
+ },
174
+ "docs/plots/lommels1.py": {
175
+ "size": 229
176
+ },
177
+ "docs/plots/lommels2.py": {
178
+ "size": 241
179
+ },
180
+ "docs/plots/pcfd.py": {
181
+ "size": 225
182
+ },
183
+ "docs/plots/spherharm40.py": {
184
+ "size": 557
185
+ },
186
+ "docs/plots/spherharm41.py": {
187
+ "size": 337
188
+ },
189
+ "docs/plots/spherharm42.py": {
190
+ "size": 337
191
+ },
192
+ "docs/plots/spherharm43.py": {
193
+ "size": 337
194
+ },
195
+ "docs/plots/spherharm44.py": {
196
+ "size": 396
197
+ },
198
+ "mpmath/__init__.py": {
199
+ "size": 8474
200
+ },
201
+ "mpmath/__main__.py": {
202
+ "size": 6465
203
+ },
204
+ "mpmath/_interactive.py": {
205
+ "size": 3089
206
+ },
207
+ "mpmath/calculus/__init__.py": {
208
+ "size": 162
209
+ },
210
+ "mpmath/calculus/approximation.py": {
211
+ "size": 9057
212
+ },
213
+ "mpmath/calculus/calculus.py": {
214
+ "size": 104
215
+ },
216
+ "mpmath/calculus/differentiation.py": {
217
+ "size": 20366
218
+ },
219
+ "mpmath/calculus/extrapolation.py": {
220
+ "size": 73176
221
+ },
222
+ "mpmath/calculus/inverselaplace.py": {
223
+ "size": 33880
224
+ },
225
+ "mpmath/calculus/odes.py": {
226
+ "size": 9877
227
+ },
228
+ "mpmath/calculus/optimization.py": {
229
+ "size": 33079
230
+ },
231
+ "mpmath/calculus/polynomials.py": {
232
+ "size": 8216
233
+ },
234
+ "mpmath/calculus/quadrature.py": {
235
+ "size": 42720
236
+ },
237
+ "mpmath/ctx_base.py": {
238
+ "size": 16843
239
+ },
240
+ "mpmath/ctx_fp.py": {
241
+ "size": 7757
242
+ },
243
+ "mpmath/ctx_iv.py": {
244
+ "size": 17221
245
+ },
246
+ "mpmath/ctx_mp.py": {
247
+ "size": 49331
248
+ },
249
+ "mpmath/ctx_mp_python.py": {
250
+ "size": 43930
251
+ },
252
+ "mpmath/function_docs.py": {
253
+ "size": 296717
254
+ },
255
+ "mpmath/functions/__init__.py": {
256
+ "size": 330
257
+ },
258
+ "mpmath/functions/bessel.py": {
259
+ "size": 39965
260
+ },
261
+ "mpmath/functions/elliptic.py": {
262
+ "size": 43539
263
+ },
264
+ "mpmath/functions/expintegrals.py": {
265
+ "size": 11947
266
+ },
267
+ "mpmath/functions/factorials.py": {
268
+ "size": 5150
269
+ },
270
+ "mpmath/functions/functions.py": {
271
+ "size": 21038
272
+ },
273
+ "mpmath/functions/hypergeometric.py": {
274
+ "size": 53702
275
+ },
276
+ "mpmath/functions/orthogonal.py": {
277
+ "size": 16487
278
+ },
279
+ "mpmath/functions/qfunctions.py": {
280
+ "size": 7831
281
+ },
282
+ "mpmath/functions/rszeta.py": {
283
+ "size": 46176
284
+ },
285
+ "mpmath/functions/signals.py": {
286
+ "size": 703
287
+ },
288
+ "mpmath/functions/theta.py": {
289
+ "size": 37320
290
+ },
291
+ "mpmath/functions/zeta.py": {
292
+ "size": 36701
293
+ },
294
+ "mpmath/functions/zetazeros.py": {
295
+ "size": 30372
296
+ },
297
+ "mpmath/identification.py": {
298
+ "size": 29377
299
+ },
300
+ "mpmath/libfp.py": {
301
+ "size": 14932
302
+ },
303
+ "mpmath/libmp/__init__.py": {
304
+ "size": 4869
305
+ },
306
+ "mpmath/libmp/backend.py": {
307
+ "size": 1654
308
+ },
309
+ "mpmath/libmp/gammazeta.py": {
310
+ "size": 71789
311
+ },
312
+ "mpmath/libmp/libelefun.py": {
313
+ "size": 44672
314
+ },
315
+ "mpmath/libmp/libhyper.py": {
316
+ "size": 35987
317
+ },
318
+ "mpmath/libmp/libintmath.py": {
319
+ "size": 14329
320
+ },
321
+ "mpmath/libmp/libmpc.py": {
322
+ "size": 27811
323
+ },
324
+ "mpmath/libmp/libmpf.py": {
325
+ "size": 57756
326
+ },
327
+ "mpmath/libmp/libmpi.py": {
328
+ "size": 27630
329
+ },
330
+ "mpmath/matrices/__init__.py": {
331
+ "size": 94
332
+ },
333
+ "mpmath/matrices/calculus.py": {
334
+ "size": 18988
335
+ },
336
+ "mpmath/matrices/eigen.py": {
337
+ "size": 24129
338
+ },
339
+ "mpmath/matrices/eigen_symmetric.py": {
340
+ "size": 57985
341
+ },
342
+ "mpmath/matrices/linalg.py": {
343
+ "size": 31900
344
+ },
345
+ "mpmath/matrices/matrices.py": {
346
+ "size": 33913
347
+ },
348
+ "mpmath/tests/test_basic_ops.py": {
349
+ "size": 23738
350
+ },
351
+ "mpmath/tests/test_bitwise.py": {
352
+ "size": 7991
353
+ },
354
+ "mpmath/tests/test_calculus.py": {
355
+ "size": 11523
356
+ },
357
+ "mpmath/tests/test_cli.py": {
358
+ "size": 4892
359
+ },
360
+ "mpmath/tests/test_compatibility.py": {
361
+ "size": 2293
362
+ },
363
+ "mpmath/tests/test_convert.py": {
364
+ "size": 12373
365
+ },
366
+ "mpmath/tests/test_demos.py": {
367
+ "size": 4386
368
+ },
369
+ "mpmath/tests/test_diff.py": {
370
+ "size": 2489
371
+ },
372
+ "mpmath/tests/test_division.py": {
373
+ "size": 6126
374
+ },
375
+ "mpmath/tests/test_eigen.py": {
376
+ "size": 4108
377
+ },
378
+ "mpmath/tests/test_eigen_symmetric.py": {
379
+ "size": 8647
380
+ },
381
+ "mpmath/tests/test_elliptic.py": {
382
+ "size": 26317
383
+ },
384
+ "mpmath/tests/test_extra_gamma.py": {
385
+ "size": 6030
386
+ },
387
+ "mpmath/tests/test_extra_zeta.py": {
388
+ "size": 933
389
+ },
390
+ "mpmath/tests/test_format.py": {
391
+ "size": 34478
392
+ },
393
+ "mpmath/tests/test_fp.py": {
394
+ "size": 96881
395
+ },
396
+ "mpmath/tests/test_functions.py": {
397
+ "size": 39289
398
+ },
399
+ "mpmath/tests/test_functions2.py": {
400
+ "size": 102669
401
+ },
402
+ "mpmath/tests/test_gammazeta.py": {
403
+ "size": 29030
404
+ },
405
+ "mpmath/tests/test_hp.py": {
406
+ "size": 10473
407
+ },
408
+ "mpmath/tests/test_identify.py": {
409
+ "size": 826
410
+ },
411
+ "mpmath/tests/test_interval.py": {
412
+ "size": 17640
413
+ },
414
+ "mpmath/tests/test_levin.py": {
415
+ "size": 5006
416
+ },
417
+ "mpmath/tests/test_linalg.py": {
418
+ "size": 11460
419
+ },
420
+ "mpmath/tests/test_matrices.py": {
421
+ "size": 9503
422
+ },
423
+ "mpmath/tests/test_module.py": {
424
+ "size": 391
425
+ },
426
+ "mpmath/tests/test_mpmath.py": {
427
+ "size": 189
428
+ },
429
+ "mpmath/tests/test_ode.py": {
430
+ "size": 1771
431
+ },
432
+ "mpmath/tests/test_pickle.py": {
433
+ "size": 400
434
+ },
435
+ "mpmath/tests/test_power.py": {
436
+ "size": 5184
437
+ },
438
+ "mpmath/tests/test_quad.py": {
439
+ "size": 4115
440
+ },
441
+ "mpmath/tests/test_rootfinding.py": {
442
+ "size": 3755
443
+ },
444
+ "mpmath/tests/test_special.py": {
445
+ "size": 2923
446
+ },
447
+ "mpmath/tests/test_str.py": {
448
+ "size": 1270
449
+ },
450
+ "mpmath/tests/test_summation.py": {
451
+ "size": 2069
452
+ },
453
+ "mpmath/tests/test_torture.py": {
454
+ "size": 9235
455
+ },
456
+ "mpmath/tests/test_trig.py": {
457
+ "size": 4854
458
+ },
459
+ "mpmath/tests/test_visualization.py": {
460
+ "size": 951
461
+ },
462
+ "mpmath/usertools.py": {
463
+ "size": 3067
464
+ },
465
+ "mpmath/visualization.py": {
466
+ "size": 10747
467
+ },
468
+ "pyproject.toml": {
469
+ "size": 2931
470
+ }
471
+ },
472
+ "processed_by": "zip_fallback",
473
+ "success": true
474
+ },
475
+ "structure": {
476
+ "packages": [
477
+ "source.mpmath",
478
+ "source.mpmath.calculus",
479
+ "source.mpmath.functions",
480
+ "source.mpmath.libmp",
481
+ "source.mpmath.matrices"
482
+ ]
483
+ },
484
+ "dependencies": {
485
+ "has_environment_yml": false,
486
+ "has_requirements_txt": false,
487
+ "pyproject": true,
488
+ "setup_cfg": false,
489
+ "setup_py": false
490
+ },
491
+ "entry_points": {
492
+ "imports": [],
493
+ "cli": [],
494
+ "modules": []
495
+ },
496
+ "llm_analysis": {
497
+ "core_modules": [
498
+ {
499
+ "package": "source.mpmath",
500
+ "module": "__init__",
501
+ "functions": [
502
+ "mp",
503
+ "fp",
504
+ "iv",
505
+ "workdps",
506
+ "workprec",
507
+ "extradps",
508
+ "extrabits",
509
+ "autoprec",
510
+ "memoize",
511
+ "maxcalls",
512
+ "monitor"
513
+ ],
514
+ "classes": [],
515
+ "description": "Primary public API surface exposing high-precision contexts and utility decorators/context managers."
516
+ },
517
+ {
518
+ "package": "source.mpmath",
519
+ "module": "ctx_mp",
520
+ "functions": [
521
+ "mpf",
522
+ "mpc",
523
+ "matrix",
524
+ "convert",
525
+ "chop",
526
+ "nstr",
527
+ "nprint",
528
+ "frac"
529
+ ],
530
+ "classes": [
531
+ "MPContext"
532
+ ],
533
+ "description": "Arbitrary-precision core context implementation used by most high-level numerical operations."
534
+ },
535
+ {
536
+ "package": "source.mpmath",
537
+ "module": "ctx_fp",
538
+ "functions": [
539
+ "sqrt",
540
+ "sin",
541
+ "cos",
542
+ "exp",
543
+ "log"
544
+ ],
545
+ "classes": [
546
+ "FPContext"
547
+ ],
548
+ "description": "Standard floating-point context with mpmath-compatible API for speed-oriented operations."
549
+ },
550
+ {
551
+ "package": "source.mpmath",
552
+ "module": "ctx_iv",
553
+ "functions": [
554
+ "mpi",
555
+ "sin",
556
+ "cos",
557
+ "exp",
558
+ "log"
559
+ ],
560
+ "classes": [
561
+ "IntervalContext"
562
+ ],
563
+ "description": "Interval arithmetic context providing enclosure-based numerical computation."
564
+ },
565
+ {
566
+ "package": "source.mpmath.calculus",
567
+ "module": "quadrature",
568
+ "functions": [
569
+ "quad",
570
+ "quadts",
571
+ "quadosc",
572
+ "quadgl"
573
+ ],
574
+ "classes": [],
575
+ "description": "Numerical integration routines (adaptive, oscillatory, Gaussian-style interfaces)."
576
+ },
577
+ {
578
+ "package": "source.mpmath.calculus",
579
+ "module": "optimization",
580
+ "functions": [
581
+ "findroot",
582
+ "multiplicity",
583
+ "steffensen"
584
+ ],
585
+ "classes": [],
586
+ "description": "Root-finding and nonlinear optimization utilities."
587
+ },
588
+ {
589
+ "package": "source.mpmath.calculus",
590
+ "module": "differentiation",
591
+ "functions": [
592
+ "diff",
593
+ "diffs",
594
+ "diffun",
595
+ "taylor"
596
+ ],
597
+ "classes": [],
598
+ "description": "Differentiation and series expansion helpers."
599
+ },
600
+ {
601
+ "package": "source.mpmath.functions",
602
+ "module": "functions",
603
+ "functions": [
604
+ "sqrt",
605
+ "exp",
606
+ "ln",
607
+ "log",
608
+ "power",
609
+ "sin",
610
+ "cos",
611
+ "tan"
612
+ ],
613
+ "classes": [],
614
+ "description": "Elementary/special function dispatch layer shared by contexts."
615
+ },
616
+ {
617
+ "package": "source.mpmath.functions",
618
+ "module": "zeta",
619
+ "functions": [
620
+ "zeta",
621
+ "altzeta",
622
+ "primezeta",
623
+ "riemannr",
624
+ "siegeltheta",
625
+ "grampoint"
626
+ ],
627
+ "classes": [],
628
+ "description": "Zeta-family and analytic number theory functions."
629
+ },
630
+ {
631
+ "package": "source.mpmath.matrices",
632
+ "module": "linalg",
633
+ "functions": [
634
+ "lu",
635
+ "qr",
636
+ "svd",
637
+ "inverse",
638
+ "det",
639
+ "cond"
640
+ ],
641
+ "classes": [],
642
+ "description": "Linear algebra decomposition and solve routines."
643
+ },
644
+ {
645
+ "package": "source.mpmath.matrices",
646
+ "module": "matrices",
647
+ "functions": [
648
+ "matrix",
649
+ "eye",
650
+ "zeros",
651
+ "ones",
652
+ "diag",
653
+ "hilbert"
654
+ ],
655
+ "classes": [
656
+ "matrix"
657
+ ],
658
+ "description": "Matrix construction/manipulation primitives and matrix type implementation."
659
+ },
660
+ {
661
+ "package": "source.mpmath.libmp",
662
+ "module": "libmpf",
663
+ "functions": [
664
+ "from_int",
665
+ "from_float",
666
+ "to_float",
667
+ "mpf_add",
668
+ "mpf_mul",
669
+ "mpf_div",
670
+ "mpf_pow_int"
671
+ ],
672
+ "classes": [],
673
+ "description": "Low-level arbitrary-precision real arithmetic backend."
674
+ }
675
+ ],
676
+ "cli_commands": [
677
+ {
678
+ "name": "python -m mpmath",
679
+ "module": "source.mpmath.__main__",
680
+ "description": "Launches mpmath interactive shell/REPL-style interface for evaluating expressions with arbitrary precision."
681
+ }
682
+ ],
683
+ "import_strategy": {
684
+ "primary": "import",
685
+ "fallback": "cli",
686
+ "confidence": 0.95
687
+ },
688
+ "dependencies": {
689
+ "required": [
690
+ "python>=3.8"
691
+ ],
692
+ "optional": [
693
+ "gmpy2",
694
+ "matplotlib"
695
+ ]
696
+ },
697
+ "risk_assessment": {
698
+ "import_feasibility": 0.95,
699
+ "intrusiveness_risk": "low",
700
+ "complexity": "medium"
701
+ }
702
+ },
703
+ "deepwiki_analysis": {
704
+ "repo_url": "https://github.com/fredrik-johansson/mpmath",
705
+ "repo_name": "mpmath",
706
+ "error": "DeepWiki analysis failed",
707
+ "model": "gpt-5.3-codex",
708
+ "source": "llm_direct_analysis",
709
+ "success": false
710
+ },
711
+ "deepwiki_options": {
712
+ "enabled": true,
713
+ "model": "gpt-5.3-codex"
714
+ },
715
+ "risk": {
716
+ "import_feasibility": 0.95,
717
+ "intrusiveness_risk": "low",
718
+ "complexity": "medium"
719
+ }
720
+ }
mpmath/mcp_output/diff_report.md ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Difference Report — `mpmath`
2
+
3
+ **Generated:** 2026-03-12 03:31:00
4
+ **Repository:** `mpmath`
5
+ **Project Type:** Python library
6
+ **Feature Scope:** Basic functionality
7
+ **Intrusiveness:** None
8
+ **Workflow Status:** ✅ Success
9
+ **Test Status:** ❌ Failed
10
+ **Changed Files:** `8 new`, `0 modified`
11
+
12
+ ---
13
+
14
+ ## 1) Executive Summary
15
+
16
+ This update introduces **8 new files** with **no direct modifications** to existing files, indicating a likely additive, low-risk change set at the source level.
17
+ However, despite successful workflow execution, the **test suite failed**, which is the primary blocker for release readiness.
18
+
19
+ **Current release recommendation:** **Do not release** until test failures are resolved and validated.
20
+
21
+ ---
22
+
23
+ ## 2) Project Overview
24
+
25
+ `mpmath` is a Python numerical library focused on arbitrary-precision arithmetic and special mathematical functions.
26
+ Given the stated scope (“Basic functionality”), this change likely targets foundational additions (e.g., utilities, docs, configuration, tests, or auxiliary modules) rather than deep architectural refactors.
27
+
28
+ ---
29
+
30
+ ## 3) Change Inventory
31
+
32
+ | Metric | Value |
33
+ |---|---|
34
+ | New files | 8 |
35
+ | Modified files | 0 |
36
+ | Deleted files | 0 (not reported) |
37
+ | Intrusiveness | None |
38
+ | CI/Workflow | Success |
39
+ | Tests | Failed |
40
+
41
+ ### Interpretation
42
+ - **No in-place edits** reduce regression risk in existing code paths.
43
+ - **New-file-only change pattern** often implies extensibility work, packaging/test additions, docs, or new modules.
44
+ - **Failed tests** suggest either:
45
+ 1. New code introduces failing expectations,
46
+ 2. Environment/dependency drift,
47
+ 3. Incomplete integration of newly added files.
48
+
49
+ ---
50
+
51
+ ## 4) Difference Analysis
52
+
53
+ ## 4.1 Structural Impact
54
+ - Additive update with no direct mutation of existing implementation files.
55
+ - Potentially clean separation, but practical impact depends on whether new files are imported/executed by runtime or test discovery.
56
+
57
+ ## 4.2 Functional Impact (Expected)
58
+ - Since the feature scope is basic, likely impact includes:
59
+ - foundational helpers,
60
+ - baseline API extension,
61
+ - test/data fixture introduction,
62
+ - packaging or project metadata support.
63
+ - No evidence of intrusive behavior or broad refactor.
64
+
65
+ ## 4.3 Risk Profile
66
+ - **Source risk:** Low (additive, non-intrusive).
67
+ - **Integration risk:** Medium (test failures indicate unresolved compatibility or correctness issue).
68
+ - **Release risk:** High until tests pass.
69
+
70
+ ---
71
+
72
+ ## 5) Technical Analysis
73
+
74
+ ## 5.1 CI vs Test Paradox
75
+ Workflow success with failed tests typically means:
76
+ - pipeline completed execution correctly,
77
+ - but one or more validation gates failed.
78
+
79
+ This is usually healthy CI behavior and indicates reliable signaling.
80
+
81
+ ## 5.2 Likely Failure Domains
82
+ Given new-file-only changes, investigate:
83
+ 1. **Test discovery conflicts** (naming, duplicate test modules, unintended collection).
84
+ 2. **Import path issues** (new modules not on path, circular imports).
85
+ 3. **Dependency/version constraints** (new file requires package absent in CI matrix).
86
+ 4. **Baseline assumptions** (precision defaults, platform-specific numeric behavior).
87
+ 5. **Configuration drift** (`pyproject.toml`, `setup.cfg`, `tox.ini`, `pytest.ini` additions not aligned).
88
+
89
+ ## 5.3 Quality Gate Status
90
+ - Build/Workflow orchestration: **Pass**
91
+ - Verification/Tests: **Fail**
92
+ - Overall quality gate: **Fail**
93
+
94
+ ---
95
+
96
+ ## 6) Recommendations & Improvements
97
+
98
+ ## 6.1 Immediate (Blocking) Actions
99
+ 1. **Triage failing tests by class**
100
+ - deterministic logic failure vs environment/setup failure.
101
+ 2. **Reproduce locally using CI-equivalent environment**
102
+ - same Python versions, dependency pins, and test command.
103
+ 3. **Isolate impact of each new file**
104
+ - disable selectively to identify triggering artifact.
105
+ 4. **Patch and rerun full suite**
106
+ - include targeted + full regression runs.
107
+
108
+ ## 6.2 Short-Term Hardening
109
+ - Add/adjust:
110
+ - explicit dependency pins/markers,
111
+ - import smoke tests for newly added modules,
112
+ - stricter lint/type checks on new files.
113
+ - Ensure test files follow consistent discovery naming conventions.
114
+ - Validate packaging manifests include/exclude new files correctly.
115
+
116
+ ## 6.3 Process Improvements
117
+ - Require **green tests** as merge gate.
118
+ - Add CI matrix checks for supported Python versions and OSes.
119
+ - Introduce a pre-merge “new-file sanity checklist”:
120
+ - importability,
121
+ - docs coverage,
122
+ - tests for each new public symbol.
123
+
124
+ ---
125
+
126
+ ## 7) Deployment Information
127
+
128
+ ## 7.1 Readiness
129
+ - **Not deployment-ready** due to failed tests.
130
+
131
+ ## 7.2 Suggested Deployment Decision
132
+ - **Hold release**.
133
+ - Create a hotfix/patch branch to resolve failures.
134
+ - Re-run CI and only proceed when:
135
+ - full test suite passes,
136
+ - no regressions observed in numerical core scenarios.
137
+
138
+ ## 7.3 Rollback Consideration
139
+ - Since no files were modified, rollback complexity is low (revert additive changeset if needed).
140
+
141
+ ---
142
+
143
+ ## 8) Future Planning
144
+
145
+ 1. **Stability-first milestone**
146
+ - close all current test failures,
147
+ - add regression tests capturing root cause.
148
+ 2. **Observability**
149
+ - improve CI logs/artifacts for quicker failure localization.
150
+ 3. **Compatibility roadmap**
151
+ - formalize version support and dependency strategy.
152
+ 4. **Incremental release policy**
153
+ - small additive batches with mandatory green gates before tagging releases.
154
+
155
+ ---
156
+
157
+ ## 9) Conclusion
158
+
159
+ The update is structurally low-intrusive (8 new files, no modified files) but currently **blocked by failing tests**.
160
+ From an engineering governance perspective, this is a **non-releasable state**.
161
+ Resolve test failures, strengthen integration checks for newly added artifacts, and rerun full validation prior to deployment.
mpmath/mcp_output/mcp_plugin/__init__.py ADDED
File without changes
mpmath/mcp_output/mcp_plugin/adapter.py ADDED
@@ -0,0 +1,325 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ import traceback
4
+ import importlib
5
+ from typing import Any, Dict, Optional, List
6
+
7
+ source_path = os.path.join(
8
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
9
+ "source",
10
+ )
11
+ sys.path.insert(0, source_path)
12
+
13
+
14
+ class Adapter:
15
+ """
16
+ MCP Import Mode Adapter for mpmath repository.
17
+
18
+ This adapter prioritizes direct Python import usage from local source code and provides
19
+ graceful fallback guidance if imports fail.
20
+
21
+ Unified return format:
22
+ {
23
+ "status": "success" | "error" | "fallback",
24
+ "mode": "import" | "fallback",
25
+ "data": Any,
26
+ "error": str | None,
27
+ "guidance": str | None
28
+ }
29
+ """
30
+
31
+ # -------------------------------------------------------------------------
32
+ # Initialization and module management
33
+ # -------------------------------------------------------------------------
34
+ def __init__(self) -> None:
35
+ self.mode = "import"
36
+ self._modules: Dict[str, Any] = {}
37
+ self._import_error: Optional[str] = None
38
+ self._load_modules()
39
+
40
+ def _result(
41
+ self,
42
+ status: str,
43
+ data: Any = None,
44
+ error: Optional[str] = None,
45
+ guidance: Optional[str] = None,
46
+ ) -> Dict[str, Any]:
47
+ return {
48
+ "status": status,
49
+ "mode": self.mode,
50
+ "data": data,
51
+ "error": error,
52
+ "guidance": guidance,
53
+ }
54
+
55
+ def _load_modules(self) -> None:
56
+ module_map = {
57
+ "mpmath": "mpmath",
58
+ "interactive": "mpmath._interactive",
59
+ "main": "mpmath.__main__",
60
+ "ctx_base": "mpmath.ctx_base",
61
+ "ctx_fp": "mpmath.ctx_fp",
62
+ "ctx_iv": "mpmath.ctx_iv",
63
+ "ctx_mp": "mpmath.ctx_mp",
64
+ "ctx_mp_python": "mpmath.ctx_mp_python",
65
+ "function_docs": "mpmath.function_docs",
66
+ "identification": "mpmath.identification",
67
+ "libfp": "mpmath.libfp",
68
+ "usertools": "mpmath.usertools",
69
+ "visualization": "mpmath.visualization",
70
+ "calculus_approximation": "mpmath.calculus.approximation",
71
+ "calculus_differentiation": "mpmath.calculus.differentiation",
72
+ "calculus_extrapolation": "mpmath.calculus.extrapolation",
73
+ "calculus_inverselaplace": "mpmath.calculus.inverselaplace",
74
+ "calculus_odes": "mpmath.calculus.odes",
75
+ "calculus_optimization": "mpmath.calculus.optimization",
76
+ "calculus_polynomials": "mpmath.calculus.polynomials",
77
+ "calculus_quadrature": "mpmath.calculus.quadrature",
78
+ "functions_bessel": "mpmath.functions.bessel",
79
+ "functions_elliptic": "mpmath.functions.elliptic",
80
+ "functions_expintegrals": "mpmath.functions.expintegrals",
81
+ "functions_factorials": "mpmath.functions.factorials",
82
+ "functions_functions": "mpmath.functions.functions",
83
+ "functions_hypergeometric": "mpmath.functions.hypergeometric",
84
+ "functions_orthogonal": "mpmath.functions.orthogonal",
85
+ "functions_qfunctions": "mpmath.functions.qfunctions",
86
+ "functions_rszeta": "mpmath.functions.rszeta",
87
+ "functions_signals": "mpmath.functions.signals",
88
+ "functions_theta": "mpmath.functions.theta",
89
+ "functions_zeta": "mpmath.functions.zeta",
90
+ "functions_zetazeros": "mpmath.functions.zetazeros",
91
+ "libmp_backend": "mpmath.libmp.backend",
92
+ "libmp_gammazeta": "mpmath.libmp.gammazeta",
93
+ "libmp_libelefun": "mpmath.libmp.libelefun",
94
+ "libmp_libhyper": "mpmath.libmp.libhyper",
95
+ "libmp_libintmath": "mpmath.libmp.libintmath",
96
+ "libmp_libmpc": "mpmath.libmp.libmpc",
97
+ "libmp_libmpf": "mpmath.libmp.libmpf",
98
+ "libmp_libmpi": "mpmath.libmp.libmpi",
99
+ "matrices_calculus": "mpmath.matrices.calculus",
100
+ "matrices_eigen": "mpmath.matrices.eigen",
101
+ "matrices_eigen_symmetric": "mpmath.matrices.eigen_symmetric",
102
+ "matrices_linalg": "mpmath.matrices.linalg",
103
+ "matrices_matrices": "mpmath.matrices.matrices",
104
+ }
105
+
106
+ try:
107
+ for key, mod_path in module_map.items():
108
+ self._modules[key] = importlib.import_module(mod_path)
109
+ self.mode = "import"
110
+ self._import_error = None
111
+ except Exception as exc:
112
+ self.mode = "fallback"
113
+ self._import_error = f"Import failed: {exc}"
114
+ self._modules = {}
115
+
116
+ def health_check(self) -> Dict[str, Any]:
117
+ """
118
+ Check adapter readiness and dependency status.
119
+ """
120
+ if self.mode == "import":
121
+ return self._result(
122
+ "success",
123
+ data={
124
+ "import_mode": True,
125
+ "repository": "mpmath",
126
+ "python_requirement": ">=3.8",
127
+ "optional_dependencies": ["gmpy2", "matplotlib"],
128
+ "loaded_modules": sorted(list(self._modules.keys())),
129
+ },
130
+ )
131
+ return self._result(
132
+ "fallback",
133
+ data={"import_mode": False},
134
+ error=self._import_error,
135
+ guidance=(
136
+ "Ensure repository source is available under './source' and retry. "
137
+ "You can also run CLI fallback with 'python -m mpmath'."
138
+ ),
139
+ )
140
+
141
+ # -------------------------------------------------------------------------
142
+ # Generic execution helpers
143
+ # -------------------------------------------------------------------------
144
+ def call_mpmath(self, function_name: str, *args: Any, **kwargs: Any) -> Dict[str, Any]:
145
+ """
146
+ Call a top-level function or access object from mpmath package.
147
+
148
+ Parameters:
149
+ function_name: Name of attribute/function in 'mpmath'.
150
+ *args/**kwargs: Forwarded to callable targets.
151
+
152
+ Returns:
153
+ Unified status dictionary with function result.
154
+ """
155
+ if self.mode != "import":
156
+ return self._result(
157
+ "fallback",
158
+ error=self._import_error,
159
+ guidance="Import mode unavailable. Use 'python -m mpmath' for interactive CLI fallback.",
160
+ )
161
+ try:
162
+ mpmath_mod = self._modules["mpmath"]
163
+ target = getattr(mpmath_mod, function_name)
164
+ if callable(target):
165
+ return self._result("success", data=target(*args, **kwargs))
166
+ return self._result("success", data=target)
167
+ except AttributeError:
168
+ return self._result(
169
+ "error",
170
+ error=f"Function or attribute '{function_name}' was not found in mpmath.",
171
+ guidance="Check function name spelling and confirm it exists in the repository version.",
172
+ )
173
+ except Exception as exc:
174
+ return self._result(
175
+ "error",
176
+ error=f"Failed to execute mpmath.{function_name}: {exc}",
177
+ guidance="Validate input arguments and numeric domains for the selected operation.",
178
+ )
179
+
180
+ def call_module_function(
181
+ self, module_key: str, function_name: str, *args: Any, **kwargs: Any
182
+ ) -> Dict[str, Any]:
183
+ """
184
+ Call a function dynamically from any loaded module.
185
+
186
+ Parameters:
187
+ module_key: Internal loaded module key (see health_check loaded_modules).
188
+ function_name: Target function or attribute name.
189
+ *args/**kwargs: Forwarded to callable targets.
190
+
191
+ Returns:
192
+ Unified status dictionary with call result.
193
+ """
194
+ if self.mode != "import":
195
+ return self._result(
196
+ "fallback",
197
+ error=self._import_error,
198
+ guidance="Import mode unavailable. Ensure source path is correct and retry.",
199
+ )
200
+ try:
201
+ mod = self._modules[module_key]
202
+ target = getattr(mod, function_name)
203
+ if callable(target):
204
+ return self._result("success", data=target(*args, **kwargs))
205
+ return self._result("success", data=target)
206
+ except KeyError:
207
+ return self._result(
208
+ "error",
209
+ error=f"Module key '{module_key}' is not loaded.",
210
+ guidance="Use health_check to inspect available module keys.",
211
+ )
212
+ except AttributeError:
213
+ return self._result(
214
+ "error",
215
+ error=f"Function or attribute '{function_name}' was not found in module '{module_key}'.",
216
+ guidance="Inspect module API and ensure the requested symbol exists.",
217
+ )
218
+ except Exception as exc:
219
+ return self._result(
220
+ "error",
221
+ error=f"Failed to execute {module_key}.{function_name}: {exc}",
222
+ guidance="Check the function signature and argument compatibility.",
223
+ )
224
+
225
+ # -------------------------------------------------------------------------
226
+ # CLI fallback support
227
+ # -------------------------------------------------------------------------
228
+ def run_cli_entry(self, argv: Optional[List[str]] = None) -> Dict[str, Any]:
229
+ """
230
+ Run repository CLI entry equivalent to `python -m mpmath`.
231
+
232
+ Parameters:
233
+ argv: Optional argv list (without program name). If omitted, empty list is used.
234
+
235
+ Returns:
236
+ Unified status dictionary.
237
+ """
238
+ try:
239
+ main_mod = importlib.import_module("mpmath.__main__")
240
+ if hasattr(main_mod, "main") and callable(main_mod.main):
241
+ result = main_mod.main(*(argv or []))
242
+ return self._result("success", data=result)
243
+ return self._result(
244
+ "error",
245
+ error="CLI module loaded, but no callable 'main' entry was found.",
246
+ guidance="Use 'python -m mpmath' directly if module-level execution is required.",
247
+ )
248
+ except Exception as exc:
249
+ return self._result(
250
+ "error",
251
+ error=f"CLI execution failed: {exc}",
252
+ guidance="Run 'python -m mpmath' in a shell to inspect interactive startup behavior.",
253
+ )
254
+
255
+ # -------------------------------------------------------------------------
256
+ # Class instance helpers (generic, for identified modules)
257
+ # -------------------------------------------------------------------------
258
+ def create_instance(
259
+ self, module_key: str, class_name: str, *args: Any, **kwargs: Any
260
+ ) -> Dict[str, Any]:
261
+ """
262
+ Create an instance from a class in a loaded module.
263
+
264
+ Parameters:
265
+ module_key: Internal loaded module key.
266
+ class_name: Class name inside the module.
267
+ *args/**kwargs: Constructor arguments.
268
+
269
+ Returns:
270
+ Unified status dictionary with created instance.
271
+ """
272
+ if self.mode != "import":
273
+ return self._result(
274
+ "fallback",
275
+ error=self._import_error,
276
+ guidance="Import mode unavailable. Verify local source layout and retry.",
277
+ )
278
+ try:
279
+ mod = self._modules[module_key]
280
+ cls = getattr(mod, class_name)
281
+ instance = cls(*args, **kwargs)
282
+ return self._result("success", data=instance)
283
+ except KeyError:
284
+ return self._result(
285
+ "error",
286
+ error=f"Module key '{module_key}' is not loaded.",
287
+ guidance="Check available modules via health_check.",
288
+ )
289
+ except AttributeError:
290
+ return self._result(
291
+ "error",
292
+ error=f"Class '{class_name}' does not exist in module '{module_key}'.",
293
+ guidance="Confirm class name and module selection.",
294
+ )
295
+ except Exception as exc:
296
+ return self._result(
297
+ "error",
298
+ error=f"Failed to instantiate {module_key}.{class_name}: {exc}",
299
+ guidance="Review constructor parameters and required types.",
300
+ )
301
+
302
+ # -------------------------------------------------------------------------
303
+ # Convenience wrappers for major module groups
304
+ # -------------------------------------------------------------------------
305
+ def call_calculus(self, function_name: str, *args: Any, **kwargs: Any) -> Dict[str, Any]:
306
+ return self.call_mpmath(function_name, *args, **kwargs)
307
+
308
+ def call_functions(self, function_name: str, *args: Any, **kwargs: Any) -> Dict[str, Any]:
309
+ return self.call_mpmath(function_name, *args, **kwargs)
310
+
311
+ def call_matrices(self, function_name: str, *args: Any, **kwargs: Any) -> Dict[str, Any]:
312
+ return self.call_mpmath(function_name, *args, **kwargs)
313
+
314
+ def get_traceback(self) -> Dict[str, Any]:
315
+ """
316
+ Return current traceback string if called inside exception context.
317
+ """
318
+ try:
319
+ return self._result("success", data=traceback.format_exc())
320
+ except Exception as exc:
321
+ return self._result(
322
+ "error",
323
+ error=f"Failed to capture traceback: {exc}",
324
+ guidance="Call this method from within an active exception handling context.",
325
+ )
mpmath/mcp_output/mcp_plugin/main.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ MCP Service Auto-Wrapper - Auto-generated
3
+ """
4
+ from mcp_service import create_app
5
+
6
+ def main():
7
+ """Main entry point"""
8
+ app = create_app()
9
+ return app
10
+
11
+ if __name__ == "__main__":
12
+ app = main()
13
+ app.run()
mpmath/mcp_output/mcp_plugin/mcp_service.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import sys
3
+ from typing import List
4
+
5
+ source_path = os.path.join(
6
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
7
+ "source",
8
+ )
9
+ if source_path not in sys.path:
10
+ sys.path.insert(0, source_path)
11
+
12
+ from fastmcp import FastMCP
13
+ import mpmath as mp
14
+
15
+ mcp = FastMCP("mpmath_service")
16
+
17
+
18
+ @mcp.tool(name="set_precision", description="Set global decimal precision for mpmath calculations.")
19
+ def set_precision(dps: int) -> dict:
20
+ """
21
+ Set mpmath decimal precision.
22
+
23
+ Parameters:
24
+ dps: Number of decimal digits to keep in mpmath.mp.dps.
25
+
26
+ Returns:
27
+ Dictionary with success/result/error.
28
+ """
29
+ try:
30
+ if dps < 2:
31
+ raise ValueError("dps must be >= 2")
32
+ mp.mp.dps = dps
33
+ return {"success": True, "result": {"dps": mp.mp.dps}, "error": ""}
34
+ except Exception as e:
35
+ return {"success": False, "result": None, "error": str(e)}
36
+
37
+
38
+ @mcp.tool(name="evaluate_expression", description="Evaluate a mathematical expression using mpmath context.")
39
+ def evaluate_expression(expression: str) -> dict:
40
+ """
41
+ Evaluate a Python expression with mpmath symbols available.
42
+
43
+ Parameters:
44
+ expression: Expression string, e.g. 'sin(pi/3) + sqrt(2)'.
45
+
46
+ Returns:
47
+ Dictionary with success/result/error.
48
+ """
49
+ try:
50
+ safe_globals = {"__builtins__": {}}
51
+ safe_locals = {name: getattr(mp, name) for name in dir(mp) if not name.startswith("_")}
52
+ value = eval(expression, safe_globals, safe_locals)
53
+ return {"success": True, "result": str(value), "error": ""}
54
+ except Exception as e:
55
+ return {"success": False, "result": None, "error": str(e)}
56
+
57
+
58
+ @mcp.tool(name="find_root", description="Find a root of a function using mpmath.findroot.")
59
+ def find_root(function_expression: str, x0: float) -> dict:
60
+ """
61
+ Find a numeric root for a single-variable function.
62
+
63
+ Parameters:
64
+ function_expression: Expression in variable x, e.g. 'cos(x)-x'.
65
+ x0: Initial guess.
66
+
67
+ Returns:
68
+ Dictionary with success/result/error.
69
+ """
70
+ try:
71
+ safe_globals = {"__builtins__": {}}
72
+ safe_locals = {name: getattr(mp, name) for name in dir(mp) if not name.startswith("_")}
73
+
74
+ def f(x):
75
+ local_ctx = dict(safe_locals)
76
+ local_ctx["x"] = x
77
+ return eval(function_expression, safe_globals, local_ctx)
78
+
79
+ root = mp.findroot(f, x0)
80
+ return {"success": True, "result": str(root), "error": ""}
81
+ except Exception as e:
82
+ return {"success": False, "result": None, "error": str(e)}
83
+
84
+
85
+ @mcp.tool(name="integrate", description="Compute definite integral using mpmath.quad.")
86
+ def integrate(function_expression: str, a: float, b: float) -> dict:
87
+ """
88
+ Compute definite integral of f(x) from a to b.
89
+
90
+ Parameters:
91
+ function_expression: Expression in variable x, e.g. 'exp(-x**2)'.
92
+ a: Lower bound.
93
+ b: Upper bound.
94
+
95
+ Returns:
96
+ Dictionary with success/result/error.
97
+ """
98
+ try:
99
+ safe_globals = {"__builtins__": {}}
100
+ safe_locals = {name: getattr(mp, name) for name in dir(mp) if not name.startswith("_")}
101
+
102
+ def f(x):
103
+ local_ctx = dict(safe_locals)
104
+ local_ctx["x"] = x
105
+ return eval(function_expression, safe_globals, local_ctx)
106
+
107
+ val = mp.quad(f, [a, b])
108
+ return {"success": True, "result": str(val), "error": ""}
109
+ except Exception as e:
110
+ return {"success": False, "result": None, "error": str(e)}
111
+
112
+
113
+ @mcp.tool(name="differentiate", description="Compute n-th derivative at a point using mpmath.diff.")
114
+ def differentiate(function_expression: str, x: float, n: int) -> dict:
115
+ """
116
+ Compute derivative of order n for f at x.
117
+
118
+ Parameters:
119
+ function_expression: Expression in variable t, e.g. 'sin(t)*exp(t)'.
120
+ x: Evaluation point.
121
+ n: Derivative order (>=1).
122
+
123
+ Returns:
124
+ Dictionary with success/result/error.
125
+ """
126
+ try:
127
+ if n < 1:
128
+ raise ValueError("n must be >= 1")
129
+ safe_globals = {"__builtins__": {}}
130
+ safe_locals = {name: getattr(mp, name) for name in dir(mp) if not name.startswith("_")}
131
+
132
+ def f(t):
133
+ local_ctx = dict(safe_locals)
134
+ local_ctx["t"] = t
135
+ return eval(function_expression, safe_globals, local_ctx)
136
+
137
+ val = mp.diff(f, x, n=n)
138
+ return {"success": True, "result": str(val), "error": ""}
139
+ except Exception as e:
140
+ return {"success": False, "result": None, "error": str(e)}
141
+
142
+
143
+ @mcp.tool(name="solve_linear_system", description="Solve a dense linear system A*x=b with mpmath matrices.")
144
+ def solve_linear_system(a_rows: List[List[float]], b_values: List[float]) -> dict:
145
+ """
146
+ Solve linear system A*x=b.
147
+
148
+ Parameters:
149
+ a_rows: Matrix rows for A.
150
+ b_values: Vector b.
151
+
152
+ Returns:
153
+ Dictionary with success/result/error.
154
+ """
155
+ try:
156
+ if len(a_rows) == 0:
157
+ raise ValueError("a_rows must not be empty")
158
+ if len(a_rows) != len(b_values):
159
+ raise ValueError("A row count must match b length")
160
+ col_count = len(a_rows[0])
161
+ if col_count == 0:
162
+ raise ValueError("A must have at least one column")
163
+ for row in a_rows:
164
+ if len(row) != col_count:
165
+ raise ValueError("All rows in A must have same length")
166
+
167
+ A = mp.matrix(a_rows)
168
+ b = mp.matrix([[v] for v in b_values])
169
+ x = mp.lu_solve(A, b)
170
+ result = [str(x[i]) for i in range(len(b_values))]
171
+ return {"success": True, "result": result, "error": ""}
172
+ except Exception as e:
173
+ return {"success": False, "result": None, "error": str(e)}
174
+
175
+
176
+ @mcp.tool(name="eigenvalues", description="Compute eigenvalues of a square matrix.")
177
+ def eigenvalues(matrix_rows: List[List[float]]) -> dict:
178
+ """
179
+ Compute eigenvalues of a square matrix.
180
+
181
+ Parameters:
182
+ matrix_rows: Square matrix rows.
183
+
184
+ Returns:
185
+ Dictionary with success/result/error.
186
+ """
187
+ try:
188
+ n = len(matrix_rows)
189
+ if n == 0:
190
+ raise ValueError("matrix_rows must not be empty")
191
+ for row in matrix_rows:
192
+ if len(row) != n:
193
+ raise ValueError("Matrix must be square")
194
+ M = mp.matrix(matrix_rows)
195
+ vals = mp.eig(M, left=False, right=False)
196
+ result = [str(v) for v in vals]
197
+ return {"success": True, "result": result, "error": ""}
198
+ except Exception as e:
199
+ return {"success": False, "result": None, "error": str(e)}
200
+
201
+
202
+ @mcp.tool(name="special_function", description="Evaluate selected special functions from mpmath.")
203
+ def special_function(function_name: str, x: float) -> dict:
204
+ """
205
+ Evaluate one supported special function at x.
206
+
207
+ Parameters:
208
+ function_name: One of ['gamma', 'zeta', 'erf', 'besselj0', 'bessely0', 'airyai', 'airybi'].
209
+ x: Input value.
210
+
211
+ Returns:
212
+ Dictionary with success/result/error.
213
+ """
214
+ try:
215
+ fn = function_name.lower().strip()
216
+ if fn == "gamma":
217
+ v = mp.gamma(x)
218
+ elif fn == "zeta":
219
+ v = mp.zeta(x)
220
+ elif fn == "erf":
221
+ v = mp.erf(x)
222
+ elif fn == "besselj0":
223
+ v = mp.besselj(0, x)
224
+ elif fn == "bessely0":
225
+ v = mp.bessely(0, x)
226
+ elif fn == "airyai":
227
+ v = mp.airyai(x)
228
+ elif fn == "airybi":
229
+ v = mp.airybi(x)
230
+ else:
231
+ raise ValueError("Unsupported function_name")
232
+ return {"success": True, "result": str(v), "error": ""}
233
+ except Exception as e:
234
+ return {"success": False, "result": None, "error": str(e)}
235
+
236
+
237
+ def create_app() -> FastMCP:
238
+ return mcp
239
+
240
+
241
+ if __name__ == "__main__":
242
+ mcp.run()
mpmath/mcp_output/requirements.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ fastmcp
2
+ fastapi
3
+ uvicorn[standard]
4
+ pydantic>=2.0.0
mpmath/mcp_output/start_mcp.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """
3
+ MCP Service Startup Entry
4
+ """
5
+ import sys
6
+ import os
7
+
8
+ project_root = os.path.dirname(os.path.abspath(__file__))
9
+ mcp_plugin_dir = os.path.join(project_root, "mcp_plugin")
10
+ if mcp_plugin_dir not in sys.path:
11
+ sys.path.insert(0, mcp_plugin_dir)
12
+
13
+ from mcp_service import create_app
14
+
15
+ def main():
16
+ """Start FastMCP service"""
17
+ app = create_app()
18
+ # Use environment variable to configure port, default 8000
19
+ port = int(os.environ.get("MCP_PORT", "8000"))
20
+
21
+ # Choose transport mode based on environment variable
22
+ transport = os.environ.get("MCP_TRANSPORT", "stdio")
23
+ if transport == "http":
24
+ app.run(transport="http", host="0.0.0.0", port=port)
25
+ else:
26
+ # Default to STDIO mode
27
+ app.run()
28
+
29
+ if __name__ == "__main__":
30
+ main()
mpmath/mcp_output/workflow_summary.json ADDED
@@ -0,0 +1,237 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "repository": {
3
+ "name": "mpmath",
4
+ "url": "https://github.com/fredrik-johansson/mpmath",
5
+ "local_path": "/Users/ghh/Documents/Code/Code2MCP-private/workspace/mpmath",
6
+ "description": "Python library",
7
+ "features": "Basic functionality",
8
+ "tech_stack": "Python",
9
+ "stars": 0,
10
+ "forks": 0,
11
+ "language": "Python",
12
+ "last_updated": "",
13
+ "complexity": "medium",
14
+ "intrusiveness_risk": "low"
15
+ },
16
+ "execution": {
17
+ "start_time": 1773257128.606097,
18
+ "end_time": 1773257334.291369,
19
+ "duration": 205.6852719783783,
20
+ "status": "success",
21
+ "workflow_status": "success",
22
+ "nodes_executed": [
23
+ "download",
24
+ "analysis",
25
+ "env",
26
+ "generate",
27
+ "run",
28
+ "review",
29
+ "finalize"
30
+ ],
31
+ "total_files_processed": 5,
32
+ "environment_type": "unknown",
33
+ "llm_calls": 0,
34
+ "deepwiki_calls": 0
35
+ },
36
+ "tests": {
37
+ "original_project": {
38
+ "passed": false,
39
+ "details": {},
40
+ "test_coverage": "100%",
41
+ "execution_time": 0,
42
+ "test_files": []
43
+ },
44
+ "mcp_plugin": {
45
+ "passed": true,
46
+ "details": {},
47
+ "service_health": "healthy",
48
+ "startup_time": 0,
49
+ "transport_mode": "stdio",
50
+ "fastmcp_version": "unknown",
51
+ "mcp_version": "unknown"
52
+ }
53
+ },
54
+ "analysis": {
55
+ "structure": {
56
+ "packages": [
57
+ "source.mpmath",
58
+ "source.mpmath.calculus",
59
+ "source.mpmath.functions",
60
+ "source.mpmath.libmp",
61
+ "source.mpmath.matrices"
62
+ ]
63
+ },
64
+ "dependencies": {
65
+ "has_environment_yml": false,
66
+ "has_requirements_txt": false,
67
+ "pyproject": true,
68
+ "setup_cfg": false,
69
+ "setup_py": false
70
+ },
71
+ "entry_points": {
72
+ "imports": [],
73
+ "cli": [],
74
+ "modules": []
75
+ },
76
+ "risk_assessment": {
77
+ "import_feasibility": 0.95,
78
+ "intrusiveness_risk": "low",
79
+ "complexity": "medium"
80
+ },
81
+ "deepwiki_analysis": {
82
+ "repo_url": "https://github.com/fredrik-johansson/mpmath",
83
+ "repo_name": "mpmath",
84
+ "error": "DeepWiki analysis failed",
85
+ "model": "gpt-5.3-codex",
86
+ "source": "llm_direct_analysis",
87
+ "success": false
88
+ },
89
+ "code_complexity": {
90
+ "cyclomatic_complexity": "medium",
91
+ "cognitive_complexity": "medium",
92
+ "maintainability_index": 75
93
+ },
94
+ "security_analysis": {
95
+ "vulnerabilities_found": 0,
96
+ "security_score": 85,
97
+ "recommendations": []
98
+ }
99
+ },
100
+ "plugin_generation": {
101
+ "files_created": [
102
+ "mcp_output/start_mcp.py",
103
+ "mcp_output/mcp_plugin/__init__.py",
104
+ "mcp_output/mcp_plugin/mcp_service.py",
105
+ "mcp_output/mcp_plugin/adapter.py",
106
+ "mcp_output/mcp_plugin/main.py",
107
+ "mcp_output/requirements.txt",
108
+ "mcp_output/README_MCP.md"
109
+ ],
110
+ "main_entry": "start_mcp.py",
111
+ "requirements": [
112
+ "fastmcp>=0.1.0",
113
+ "pydantic>=2.0.0"
114
+ ],
115
+ "readme_path": "/Users/ghh/Documents/Code/Code2MCP-private/workspace/mpmath/mcp_output/README_MCP.md",
116
+ "adapter_mode": "import",
117
+ "total_lines_of_code": 0,
118
+ "generated_files_size": 0,
119
+ "tool_endpoints": 0,
120
+ "supported_features": [
121
+ "Basic functionality"
122
+ ],
123
+ "generated_tools": [
124
+ "Basic tools",
125
+ "Health check tools",
126
+ "Version info tools"
127
+ ]
128
+ },
129
+ "code_review": {},
130
+ "errors": [],
131
+ "warnings": [],
132
+ "recommendations": [
133
+ "add CI test status reporting and badges (unit",
134
+ "coverage",
135
+ "docs) since current test status is empty",
136
+ "add MCP plugin smoke/integration tests under `mcp_output/tests_mcp` for key contexts (`mp`",
137
+ "`fp`",
138
+ "`iv`) and high-risk numerics (`findroot`",
139
+ "`quad`",
140
+ "`zeta`)",
141
+ "deduplicate/namespace MCP endpoints to avoid collisions (`sin`",
142
+ "`cos`",
143
+ "`exp`",
144
+ "`log`",
145
+ "`matrix` appear multiple times)",
146
+ "generate structured tool metadata (module/context/origin) for each exported endpoint to improve discoverability",
147
+ "add property-based numerical tests (e.g.",
148
+ "Hypothesis) for algebraic identities and interval enclosure invariants",
149
+ "expand edge-case regression tests for precision/context switching (`workdps`",
150
+ "`extradps`",
151
+ "`autoprec`) and cross-context consistency",
152
+ "enforce stricter static quality gates (ruff/flake8 + mypy on plugin code",
153
+ "optional gradual typing in core hotspots)",
154
+ "add performance benchmarks (asv/pytest-benchmark) for core kernels (`libmpf`",
155
+ "`gammazeta`",
156
+ "quadrature",
157
+ "linear algebra) with CI trend tracking",
158
+ "split very large modules (`function_docs.py`",
159
+ "`test_functions2.py`",
160
+ "`ctx_mp*.py`) into smaller maintainable units",
161
+ "document optional dependency behavior (`gmpy2`",
162
+ "`matplotlib`) with fallback/perf expectations",
163
+ "add API compatibility tests for `python -m mpmath` CLI and MCP adapter import mode",
164
+ "harden packaging/reproducibility by pinning MCP plugin dependency ranges and adding lockfile or constraints",
165
+ "improve docs automation by validating `docs/plots` scripts and ensuring deterministic plot builds in CI",
166
+ "add release safeguards (changelog validation",
167
+ "version/tag consistency checks",
168
+ "publish dry-run)",
169
+ "introduce security hygiene checks (pip-audit/Safety",
170
+ "GitHub dependency review)",
171
+ "add observability to MCP service (structured logging",
172
+ "request timing",
173
+ "failure categorization)",
174
+ "create contributor-facing architecture docs mapping contexts/functions/libmp layers and MCP exposure rules"
175
+ ],
176
+ "performance_metrics": {
177
+ "memory_usage_mb": 0,
178
+ "cpu_usage_percent": 0,
179
+ "response_time_ms": 0,
180
+ "throughput_requests_per_second": 0
181
+ },
182
+ "deployment_info": {
183
+ "supported_platforms": [
184
+ "Linux",
185
+ "Windows",
186
+ "macOS"
187
+ ],
188
+ "python_versions": [
189
+ "3.8",
190
+ "3.9",
191
+ "3.10",
192
+ "3.11",
193
+ "3.12"
194
+ ],
195
+ "deployment_methods": [
196
+ "Docker",
197
+ "pip",
198
+ "conda"
199
+ ],
200
+ "monitoring_support": true,
201
+ "logging_configuration": "structured"
202
+ },
203
+ "execution_analysis": {
204
+ "success_factors": [
205
+ "Workflow status is success with all planned nodes executed (download, analysis, env, generate, run, review, finalize).",
206
+ "Import-based adapter strategy is highly feasible for mpmath (import_feasibility 0.95, low intrusiveness risk).",
207
+ "Generated MCP plugin started healthy over stdio and passed plugin-level checks.",
208
+ "Repository structure and core modules were correctly discovered, enabling broad endpoint exposure."
209
+ ],
210
+ "failure_reasons": [
211
+ "No hard workflow failure occurred.",
212
+ "DeepWiki analysis failed (non-blocking), reducing external architectural/context enrichment.",
213
+ "Original project test execution is effectively absent despite reporting 100% coverage (passed=false, no test files, zero execution time), indicating a test instrumentation/reporting defect.",
214
+ "Generated artifact metrics are inconsistent (0 LOC/size/tools despite endpoint list), indicating telemetry/measurement pipeline issues."
215
+ ],
216
+ "overall_assessment": "good",
217
+ "node_performance": {
218
+ "download_time": "Completed successfully via zip fallback; reliable but likely slower/less metadata-rich than native VCS clone.",
219
+ "analysis_time": "Completed with medium-complexity repo analysis across ~155 files; module and package extraction quality is strong.",
220
+ "generation_time": "Completed and produced expected MCP scaffold files; endpoint extraction appears broad but metric reporting is inconsistent.",
221
+ "test_time": "Plugin health test passed quickly; original project tests did not run meaningfully, leaving functional confidence gap."
222
+ },
223
+ "resource_usage": {
224
+ "memory_efficiency": "Unknown in practice: reported memory usage is 0 MB, which indicates missing telemetry rather than true zero use.",
225
+ "cpu_efficiency": "Unknown in practice: reported CPU usage is 0%, likely uncollected metrics.",
226
+ "disk_usage": "Low-to-moderate expected for generated plugin files, but reported generated size is 0, indicating measurement gap."
227
+ }
228
+ },
229
+ "technical_quality": {
230
+ "code_quality_score": 76,
231
+ "architecture_score": 82,
232
+ "performance_score": 61,
233
+ "maintainability_score": 73,
234
+ "security_score": 85,
235
+ "scalability_score": 72
236
+ }
237
+ }
mpmath/source/.DS_Store ADDED
Binary file (6.15 kB). View file
 
mpmath/source/.codecov.yml ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ coverage:
2
+ precision: 0
3
+ round: down
4
+ status:
5
+ patch:
6
+ default:
7
+ target: 97
8
+ project:
9
+ default:
10
+ threshold: 1%
11
+ comment: false
mpmath/source/.readthedocs.yaml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+ formats:
3
+ - htmlzip
4
+ - pdf
5
+ build:
6
+ os: ubuntu-22.04
7
+ tools:
8
+ python: "3"
9
+ jobs:
10
+ post_checkout:
11
+ - git fetch --unshallow
12
+ python:
13
+ install:
14
+ - method: pip
15
+ path: .
16
+ extra_requirements:
17
+ - docs
18
+ sphinx:
19
+ fail_on_warning: true
20
+ configuration: docs/conf.py
mpmath/source/CHANGES ADDED
@@ -0,0 +1,1257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ --1.4.0--
2
+ Released February 23, 2026
3
+
4
+ Features:
5
+
6
+ * Support underscores as digit separators per PEP 515, see #661 (Sergey B
7
+ Kirpichev)
8
+ * Add rationals converter for mpf's, see #666 (Sergey B Kirpichev)
9
+ * Rewrite bernpoly/eulerpoly to avoid dependency on bernoulli(1) convention,
10
+ see #700 (Sergey B Kirpichev)
11
+ * Support base kwarg for from_str(), see #703 (Jonathan Warner, Sergey B
12
+ Kirpichev)
13
+ * Support randmatrix() for mp.iv and mp contexts, see #527 (Maximilian
14
+ Gaukler)
15
+ * Added rank() function for matrices, see #610 (Jan-Philipp Hoffmann)
16
+ * Add plus flag to select the B_1 sign convention for bernoulli/bernfrac, see
17
+ #724 (Jeremy Tan Jie Rui, Sergey B Kirpichev)
18
+ * Add mpf.as_integer_ratio() method, support construction of mpf from Decimal
19
+ objects, see #731 (Sergey B Kirpichev)
20
+ * Expose lower/upper_gamma functions, see #740 (Sergey B Kirpichev)
21
+ * Support mpc initialization from string, see #743 (Sergey B Kirpichev)
22
+ * Support asinh/acosh/atanh in the fp context, see #750 (Sergey B Kirpichev)
23
+ * Support binary/octal/hexadecimal string output, see #711 (Jonathan Warner,
24
+ Sergey B Kirpichev)
25
+ * Support pickling for matrices and mpi, see #761 (Sergey B Kirpichev)
26
+ * Support matrix.__array__() dunder method, see #767 (Sergey B Kirpichev)
27
+ * Support more number syntaxes, see #778 (Sergey B Kirpichev)
28
+ * Run mpmath as a module for interactive work, see #773, #923, #931, #936,
29
+ #939 and #954 (Sergey B Kirpichev)
30
+ * Add signed option to to_man_exp(), see #783 (Sergey B Kirpichev)
31
+ * Add fp.hypot, see #798 (Sergey B Kirpichev)
32
+ * Support inf/nan's in ctx.almosteq(), #802 (Sergey B Kirpichev)
33
+ * Implement mpf.__format__(), see #819, #831, #850, #859, #857, #862, #881,
34
+ #944 and #966 (Javier Garcia, Sergey B Kirpichev)
35
+ * Support conversion from scalar ndarray's, see #821 (Sergey B Kirpichev)
36
+ * Support rounding modes in mpf.__format__, see #823, #831, #834
37
+ and #969 (Javier Garcia, Sergey B Kirpichev)
38
+ * Support '%' presentation type for mpf, see #847 (Sergey B Kirpichev)
39
+ * Support gmpy2-like rounding modes in to_str(), see #830 (Javier Garcia)
40
+ * Implement 'a'/'A' formating types for mpf.__format__, see #841 and #870
41
+ (Sergey B Kirpichev)
42
+ * Add mpc.__format__(), see #855 (Sergey B Kirpichev)
43
+ * Now mpf.__round__() returns mpf, see #826 and #966 (Sergey B Kirpichev)
44
+ * Support 'b' (binary) format type for mpf/mpc, see #867 (Sergey B Kirpichev)
45
+ * Implement mpf.__floordiv__() and mpf.__divmod__(), see #873 (Sergey B
46
+ Kirpichev)
47
+ * Add parameters for MPContext constructor, see #876 and #963 (Sergey B Kirpichev)
48
+ * Add MPFR-compatible aliases for rounding modes, see #892 (Sergey B
49
+ Kirpichev)
50
+ * Support negative indexes in matrix, see #897 (Riccardo Orsi)
51
+ * Better introspection support for decorated functions, see #900 (Sergey B
52
+ Kirpichev)
53
+ * Add moving sofa demo, see #924 (Sergey B Kirpichev)
54
+ * Support spherical Bessel functions (jn/yn), #935 (Sergey B Kirpichev)
55
+ * Add pretty_dps context property to control number of printed digits, see
56
+ #933 (Sergey B Kirpichev)
57
+ * Support thousands separators for formatting of fractional part, see #925 and
58
+ #936 (Sergey B Kirpichev)
59
+ * Use PyREPL, as fallback (no IPython), see #941 (Sergey B Kirpichev)
60
+ * Add exp2() and log2(), see #948 (Sergey B Kirpichev)
61
+ * Support rounding property for the mp context, see #963 (Sergey B Kirpichev)
62
+ * Add Fox H-function with rational A/B parameters (foxh()), see #982 (Hongren Zheng)
63
+ * Provide experimental support for free-threading builds, see #993 (Sergey B Kirpichev)
64
+
65
+ Compatibility:
66
+
67
+ * Drop Python 2 support, see #629 (Fangchen Li)
68
+ * Drop support for Python versions < 3.9, see #675 and #911 (Sergey B Kirpichev)
69
+ * Drop private mpq class, use Rational's, provided by backend, see #691 and
70
+ #769 (Sergey B Kirpichev)
71
+ * Drop to_pickable()/from_pickable() helpers, see #667 and #769 (Sergey B
72
+ Kirpichev)
73
+ * Direct access to _mpf_ tuples now deprecated, please use from/to_man_exp()
74
+ functions and special constants (finf, fninf and fnan), see
75
+ #783 (Sergey B Kirpichev)
76
+ * Removed sage backend, see #732 (Sergey B Kirpichev)
77
+ * Drop MPMATH_STRICT environment variable, see #759 (Sergey B Kirpichev)
78
+ * Deprecate current (descending) order of coefficients in polyval(), etc, see
79
+ #779, #844 and #845 (Sergey B Kirpichev, Warren Weckesser)
80
+ * Deprecate mpmath.math2, see #769 (Sergey B Kirpichev)
81
+ * Importing from the mpmath.libmp submodules is deprecated, use instead ``from
82
+ mpmath.libmp import foo``, see
83
+ issue https://github.com/mpmath/mpmath/issues/704#issuecomment-2953536980
84
+ for available functions (Sergey B Kirpichev)
85
+ * Deprecate bitcount function, see #721 and #955 (Sergey B Kirpichev)
86
+ * Deprecate mpf/mpc_log, see #989 (Sergey B Kirpichev)
87
+ * Deprecate fp.is_special(), see #1042 (Sergey B Kirpichev)
88
+
89
+ Bug fixes:
90
+
91
+ * sum_accurately(), betainc() and power() fixes, see #664 (Sergey B Kirpichev)
92
+ * Warn users about Python's true division, see #670 (Sergey B Kirpichev)
93
+ * Propagate nan's in ei_asympt(), see #672 (Sergey B Kirpichev)
94
+ * Fix matrix.__eq__, fix string parsing with underscores, see #679 (Sergey B
95
+ Kirpichev)
96
+ * Raise IndexError if matrix index out of bounds, see #689 (Sergey B
97
+ Kirpichev)
98
+ * Fix nan handling in fp.mag() and hyper(), see #688 (Sergey B Kirpichev)
99
+ * Optimize sparse matrix dot product, see #450 (Tyler Chen)
100
+ * Correct pow() for mpf's to be consistent with mpfr/float's, see #690 (Sergey
101
+ B Kirpichev)
102
+ * Improve hypsum non-convergence behaviour, see #703 (Benjamin Fischer)
103
+ * Fixed TypeError in LU_comp, see #610 (Jan-Philipp Hoffmann)
104
+ * Fix disagreement fp.mod vs mp.mod, see #710 (Sergey B Kirpichev)
105
+ * Skip eigenvectors if left=right=False for one-dimentional matrix, see #713
106
+ (Sergey B Kirpichev)
107
+ * Fix mpc() constructor to be compatible with complex(), fix disagreement
108
+ fp.pow vs mp.pow, see #731 (Sergey B Kirpichev)
109
+ * Add derivative keyword argument for besselk(), see #735 (Sergey B Kirpichev)
110
+ * Fix quadosc(), fast case in _hyp2f1(), correct fp.gamma() and fp.isnprint(),
111
+ see #740 (Sergey B Kirpichev)
112
+ * Pevent erroneous setting of dps/prec on mpmath module, see #678
113
+ (Colin B. Macdonald)
114
+ * Update splot() for recent matplotlib, see #747 (Sergey B Kirpichev)
115
+ * acos_asin(): don't try to normalize special numbers, fix repr(mp.eps), see
116
+ #750 (Sergey B Kirpichev)
117
+ * Fix choleksy_solve for complex matrix, see #755 (Qiming Sun)
118
+ * Fix hang in polylog_general(), fix demos, use cholesky_solve() for
119
+ overdetermined complex linear systems, fix several issues with empty
120
+ matrices, see #759
121
+ * sqrt(z): special case for infinite z.imag, see #777 (Sergey B Kirpichev)
122
+ * Correct atan2(±inf, ±inf), see #775 (Sergey B Kirpichev)
123
+ * Handle infinite arguments in tan/tanh, see #785 (Sergey B Kirpichev)
124
+ * Drop mpf.__complex__(), workaround 1/z division for acot/asec/acsc/acoth,
125
+ see #797 (Sergey B Kirpichev)
126
+ * Handle more special cases in besselk and hyp1f1, see #792, #800 and #801
127
+ (Sergey B Kirpichev)
128
+ * Correct asin/acos for infinite arguments, see #795 (Sergey B Kirpichev)
129
+ * Reduce memory usage for QuadratureRule cache, see #812 (Sergey B Kirpichev)
130
+ * Drop sign from nstr(mpf('inf')) output, see #828 (Sergey B Kirpichev)
131
+ * Improve accuracy of log1p(), see #803 and #854 (Tim Peters, Sergey B
132
+ Kirpichev)
133
+ * Normalize mpf in mp.npconvert(), fix special cases in bernpoly(), see #839
134
+ (Sergey B Kirpichev)
135
+ * Fix mpf_div() for prec=0, see #849 (Sergey B Kirpichev)
136
+ * Raise ValueError for complex infininity condition in zeta(s, a), see #864
137
+ (Sergey B Kirpichev)
138
+ * Enable trap_complex for MDNewton, see #870 (Sergey B Kirpichev)
139
+ * Use correct mixed-mode functions in fsub/fdiv, add special cases for
140
+ infinities in mpc_*div(), see #873 (Sergey B Kirpichev)
141
+ * Revert "fix ellippi to return an inf instead of raising an exception", see
142
+ #875 (Sergey B Kirpichev)
143
+ * Reject invalid strings in from_str(), see #886 (Sergey B Kirpichev)
144
+ * Use parity formula for besseli, see #889 (Sergey B Kirpichev)
145
+ * Special case in ctx.hypsum for infinite z, see #902 (Sergey B Kirpichev)
146
+ * Raise an exception if iv's comparison can't be decided, see #903 (Sergey B
147
+ Kirpichev)
148
+ * Add special case for ±inf in polylog_continuation(), see #904, #1034
149
+ and #1037 (Sergey B Kirpichev, Colin B. Macdonald)
150
+ * Increase working precision in polylog_general() for negative s, see #898
151
+ (Sergey B Kirpichev)
152
+ * Correct case for integer n in besselj/besseli, see #909 (Sergey B Kirpichev)
153
+ * Use sum_accurately() in hankel1/2(), see #926 (Sergey B Kirpichev)
154
+ * Ensure mpf_bernoulli() returns normalized answer, see #939 (Sergey B
155
+ Kirpichev)
156
+ * Use mpf_log1p in acos_asin() helper (implementing Hull et al algorithm), see
157
+ #948 and #1036 (Sergey B Kirpichev)
158
+ * Fix kwargs passing in the nstr() for mpc, see #964 (David Walker)
159
+ * Fix exception type for int(inf), see #966 (Sergey B Kirpichev)
160
+ * Ensure exp, sin, tan, etc have a correct __name__ attribute, see #997
161
+ (Warren Weckesser)
162
+ * Matrix raise ValueError in case of negative dimensions, see #1004 (Ayush
163
+ Baranwal)
164
+ * Support lists in sinm() and cosm(), see #1003 (Ayush Baranwal)
165
+ * Properly handle nan's elliprj(), see #1038 (Sergey B Kirpichev)
166
+ * Raise ValueError for logm(0), see #1017 (Ayush Baranwal)
167
+ * Fix erf(z) with re(z) of large magnitude, see #1039 (Sergey B Kirpichev)
168
+ * Return nan's for polylog(s, nan) or polylog(s, nan+nanj),
169
+ see #1041 (Sergey B Kirpichev)
170
+ * Fix fp.isnormal() for subnormals, see #1042 (Sergey B Kirpichev)
171
+
172
+ Maintenance:
173
+
174
+ * Use codecov/coverage-action, see #674 (Sergey B Kirpichev)
175
+ * Run CI tests with pytest-xdist, see #685 (Sergey B Kirpichev)
176
+ * Add pyproject.toml, depend on flake518, see #684 (Sergey B Kirpichev)
177
+ * Port torture.py/extratest_zeta.py/extratest_gamma.py to the pytest
178
+ framework, see #687 (Sergey B Kirpichev)
179
+ * Create CITATION.bib, see #681 (Devharsh Trivedi)
180
+ * Avoid using star imports in tests and documentation, see #698 (Sergey B
181
+ Kirpichev)
182
+ * Fix some py2's remnants and remove old gmpy workarounds, see #699 (Sergey B
183
+ Kirpichev)
184
+ * Use math.isqrt in isqrt_python calculations, see #695 (Daiki Takahashi)
185
+ * Use gcd() and other bigint's functions from the backend, see #697 (Sergey B
186
+ Kirpichev)
187
+ * Drop legacy and redundant code, see #701 (Sergey B Kirpichev)
188
+ * Change FPContext to use more functions from the stdlib, see #692 (Sergey B
189
+ Kirpichev)
190
+ * Avoid dynamic method creation in _mpf, see #702 (Sergey B Kirpichev)
191
+ * Enable testing on CPython 3.12-dev, see #706 (Sergey B Kirpichev)
192
+ * Use bit_length() method instead of bitcount(), see #721 (Sergey B Kirpichev)
193
+ * Use lru_cache() in ifib() and eulernum(), isprime() alternatives from
194
+ backends, see #722 (Sergey B Kirpichev)
195
+ * Use setuptools_scm to update __version__, see #694 (Sergey B Kirpichev)
196
+ * Run tests on 3.13, see #759 (Sergey B Kirpichev)
197
+ * Do not build depend on pip and wheel, see #758 (Gonzalo Tornaría)
198
+ * Add CONTRIBUTING.rst, see #763 (Sergey B Kirpichev)
199
+ * Simplify ctx_mp_python.py, see #806 (Sergey B Kirpichev)
200
+ * Update gmpy2 deps, see #808 and #813 (Sergey B Kirpichev)
201
+ * Enable testing on 3.14, see #851 (Sergey B Kirpichev)
202
+ * Refactor Github Actions, see #905 (Sergey B Kirpichev)
203
+ * Build and publish wheel, see #913 (David Hotham)
204
+ * Use the intended setuptools_scm integration pattern, see #940 (Ronny
205
+ Pfannschmidt)
206
+ * Add backport action, see #1042 (Sergey B Kirpichev)
207
+
208
+ See the release milestone (1.4) for a complete list of issues and pull requests
209
+ involved in this release.
210
+
211
+
212
+ --1.3.0--
213
+ Released March 7, 2023
214
+
215
+ Security issues:
216
+
217
+ * Fixed ReDOS vulnerability in mpmathify() (CVE-2021-29063) (Vinzent Steinberg)
218
+
219
+ Features:
220
+
221
+ * Added quadsubdiv() for numerical integration with adaptive path splitting
222
+ (Fredrik Johansson)
223
+ * Added the Cohen algorithm for inverse Laplace transforms
224
+ (Guillermo Navas-Palencia)
225
+ * Some speedup of matrix multiplication (Fredrik Johansson)
226
+ * Optimizations to Carlson elliptic integrals (Paul Masson)
227
+ * Added signal functions (squarew(), trianglew(), sawtoothw(), unit_triangle()
228
+ sigmoidw()) (Nike Dattani, Deyan Mihaylov, Tina Yu)
229
+
230
+ Bug fixes:
231
+
232
+ * Correct mpf initialization from tuple for finf and fninf (Sergey B Kirpichev)
233
+ * Support QR decomposition for matrices of width 0 and 1 (Clemens Hofreither)
234
+ * Fixed some cases where elliprj() gave inaccurate results (Fredrik Johansson)
235
+ * Fixed cases where digamma() hangs for complex input (Fredrik Johansson)
236
+ * Fixed cases of polylog() with integer-valued parameter with complex type
237
+ (Fredrik Johansson)
238
+ * Fixed fp.nsum() with Euler-Maclaurin algorithm (Fredrik Johansson)
239
+
240
+ Maintenance:
241
+
242
+ * Dropped support for Python 3.4 (Sergey B Kirpichev)
243
+ * Documentation cleanup (Sergey B Kirpichev)
244
+ * Removed obsolete files (Sergey B Kirpichev)
245
+ * Added options to runtests.py to skip tests and exit on failure
246
+ (Jonathan Warner)
247
+
248
+
249
+ --1.2.0--
250
+ Released February 1, 2021
251
+
252
+ Features and optimizations:
253
+
254
+ * Support @ operator for matrix multiplication (Max Gaukler)
255
+ * Add eta() implementing the Dedekind eta function
256
+ * Optimized the python_trailing function (adhoc-king)
257
+ * Implement unary plus for matrices (Max Gaukler)
258
+ * Improved calculation of gram_index (p15-git-acc)
259
+
260
+ Compatibility:
261
+
262
+ * Enable sage backend by default only if SAGE_ROOT is set (Pauli Virtanen)
263
+ * Fix syntax warnings on CPython 3.8 (Sergey B Kirpichev)
264
+ * Changed version requirements to Python 2.7 and 3.4 or later
265
+ (Sergey B Kirpichev)
266
+ * Improvements to the setup and test code (Sergey B Kirpichev)
267
+ * Fix sys.version comparisons for compatibility with Python 3.10 (Jakub Wilk)
268
+ * Fixes to Python2/3 compatibility for printing (Christian Clauss)
269
+
270
+ Bug fixes:
271
+
272
+ * Fix a possible division by zero in shanks() (Pascal Hebbeker)
273
+ * Fixed indexing errors in deHoog, Knight & Stokes inverse laplace
274
+ transform algorithm (Kris Kuhlman)
275
+ * Corrected branch cuts of the elliprj() function in some cases
276
+ * Fix initialization of iv.matrix from non-interval matrix (Max Gaukler)
277
+ * Preserve function signatures in PrecisionManager (Viet Tran)
278
+ * Implemented float and complex conversions for ivmpf
279
+ (Jonathan Warner)
280
+ * Fixed issue with scalar-matrix multiplication for interval matrices
281
+ (Jonathan Warner)
282
+ * Fix estimation of quadrature error with multiple subintervals (Tom Minka)
283
+ * Fixed a problem with the defun decorators (Sergey B Kirpichev)
284
+ * Fix eigenvalue sorting by absolute value (Georg Ostrovski)
285
+
286
+ Cleanup:
287
+
288
+ * Documentation corrections (Paul Masson, S.Y. Lee)
289
+ * Remove inaccessible logic in fsum/fdot (Sergey B Kirpichev)
290
+ * Remove broken force_type option for matrix constructor (Max Gaukler)
291
+ * Fix text of the BSD license in LICENSE (Sergey B Kirpichev)
292
+ * Minor code cleanup (Frédéric Chapoton)
293
+ * Removed old, unused code
294
+
295
+
296
+ --1.1.0--
297
+ Released December 11, 2018
298
+
299
+ Bugs:
300
+ * Fixed severe bug in householder() for complex matrices
301
+ (Michael Kagalenko)
302
+ * Fixed frequently-reported bug where findroot() mysteriously raised
303
+ UnboundLocalError (Sergey B Kirpichev)
304
+ * Corrected rounding in binary-to-decimal conversion above 500 digits
305
+ * Fixed minor loss of accuracy affecting rf(), ff(), binomial(), beta()
306
+ * Fixed incorrect computation of the Hurwitz zeta function in some cases
307
+ * Fixed accuracy of digamma function near 0
308
+ * Fixed RuntimeError in qfac() in Python 3.7 caused by raising
309
+ StopIteration (Zbigniew Jędrzejewski-Szmek)
310
+ * Fix to allow NumPy arrays in fdot() (Nico Schlömer)
311
+
312
+ Features and improvements:
313
+ * Added more automatic conversions from Fraction, Decimal, NumPy types
314
+ (Jonathan Warner)
315
+ * Support creating mpf from a long literal (ylemkimon)
316
+ * Implemented log1p()
317
+ * Slight speedup of eig()
318
+ * Implement polylog() for general complex s and z by using Hurwitz zeta
319
+ algorithm as a fallback
320
+
321
+ Library:
322
+ * Test more CPython and PyPy versions (Sergey B Kirpichev, Aaron Meurer)
323
+ * Drop support for Python 2.6 and 3.2 (Sergey B Kirpichev)
324
+ * Use py.test for test code; lots of code cleanup (Sergey B Kirpichev)
325
+ * Corrections to the documentation (Paul Masson, Connor Behan,
326
+ Warren Weckesser, Aaron Meurer)
327
+
328
+ --1.0.0--
329
+ Released September 27, 2017
330
+
331
+ * Bumped to major version number for 10 year anniversary
332
+ * Added module for inverse Laplace transforms, including the top level
333
+ function invertlaplace() as well as several different algorithms
334
+ (Talbot, Gaver-Stehfest and de Hoog) implemented in
335
+ mpmath.calculus.inverselaplace (Kris Kuhlman)
336
+ * Fixed bugs in elliprg() giving incorrect values for certain input
337
+ * Fixed wrong degree 1 nodes for Gaussian quadrature
338
+ * Made make acot(0) and acoth(0) return a finite result
339
+ * Fixed sieved zeta sum not being used in Python 3, and added cutoff
340
+ for sieved zeta sum on 32-bit systems when too much memory would be used
341
+ * Fixed zeta(0,0.5) to return correct value instead of raising
342
+ NoConvergence exception
343
+ * Added detection of exact zeros in gammainc(), in particular fixing
344
+ NoConvergence error for gammainc(3,-1+1j)
345
+ * Fixed wrong values from besseli() due to improper internal precision
346
+ * Fixed bessely(0,1j) to return complex nan instead of raising NameError
347
+ (Paul Masson)
348
+ * Changed float() and complex() applied to an mpf or mpc to use rounding
349
+ to nearest (or the context rounding mode) instead truncating
350
+ * Fix imaginary part of gammainc(n,x), n negative odd int, x < 0
351
+ * Added alternative "phase" color scheme to cplot()
352
+ * Better error message for int(inf) or int(nan) (Aaron Meurer)
353
+ * Fixed polyroots() with error=True
354
+ * Added support to pass optional initial values to polyroots()
355
+ (Michael Kagalenko)
356
+ * Rewrote the Python major version selection to make it work if something
357
+ else has redefined xrange (Arne Brys)
358
+ * Switched documentation formula rendering to MathJax (Sergey B Kirpichev)
359
+ * Fixed documentation TeX build (Sergey B Kirpichev)
360
+ * Added PEP8 conformity testing (Sergey B Kirpichev)
361
+ * Various fixes for the test code and test infrastructure on different
362
+ platforms and Python versions (Sergey B Kirpichev)
363
+ * Fixed module paths in setup.py (Aaron Meurer)
364
+ * Documented more options for methods such as nstr() and hyper()
365
+ * Miscellaneous corrections to the documentation (various)
366
+
367
+ --0.19--
368
+ Released June 10, 2014
369
+
370
+ * Moved issue tracking to github and the main website to mpmath.org.
371
+ Several URLs and issue numbers were updated in the documentation
372
+ (Sergey B Kirpichev)
373
+ * Enabled automatic testing with Travis CI (Sergey B Kirpichev)
374
+ * Fixed many doctest issues (Sergey B Kirpichev)
375
+ * Converted line endings to LF (Ondrej Certik)
376
+ * Made polyroots() more robust (Ondrej Certik)
377
+
378
+ --0.18--
379
+ Released December 31, 2013
380
+
381
+ Linear algebra:
382
+ * added qr() for matrix QR factorization (contributed by Ken Allen)
383
+ * added functions eigsy(), eighe(), eig() to compute matrix
384
+ eigenvalues (contributed by Timo Hartmann)
385
+ * added functions svd(), svd_r(), svd_c() for singular value
386
+ decomposition of matrices (contributed by Timo Hartmann)
387
+ * added calculation of Gaussian quadrature rules for various weight
388
+ functions (contributed by Timo Hartmann)
389
+ * improved precision selection in exp_pade() (contributed by
390
+ Mario Pernici)
391
+
392
+ Special functions:
393
+ * fixed ellippi() to return an inf instead of raising an exception
394
+ * fixed a crash in zeta() with huge arguments
395
+ * added functions for computing Stirling numbers
396
+ (stirling1(), stirling2())
397
+ * improved the computation of zeros of zeta at high precision
398
+ (contributed by Juan Arias de Reyna)
399
+ * fixed zeta(-x) raising an exception for tiny x
400
+ * recognize when lerchphi() can call zeta() or polylog(),
401
+ handling those cases faster
402
+
403
+ Compatibility:
404
+ * fixed gmpy2 compatibility issues (contributed by Case Van Horsen)
405
+ * better solutions for python 2/3 compatibility,
406
+ using Benjamin Peterson's six.py
407
+ * fixes to allow mpmath to run in non-sage mode when sage is available
408
+ * support abstract base classes (contributed by Stefan Krastanov)
409
+ * use new-style classes to improve pypy performance
410
+
411
+ Other:
412
+ * added Levin, Sidi-S and Cohen/Villegas/Zagier series
413
+ transformations (contributed by Timo Hartmann)
414
+ * added isfinite() utility function
415
+ * fixed a problem with bisection root-finding
416
+ * fixed several documentation errors
417
+ * corrected number of coefficients returned by diffs() with
418
+ method='quad'
419
+ * fixed repr(constant) being slow at high precision
420
+ * made intervals hashable
421
+
422
+ --0.17--
423
+ Released February 1, 2011
424
+
425
+ Compatibility:
426
+
427
+ * Python 3 is now supported
428
+ * Dropped Python 2.4 compatibility
429
+ * Fixed Python 2.5 compatibility in matrix slicing code
430
+ * Implemented Python 3.2-compatible hashing, making mpmath numbers
431
+ hash compatible with extremely large integers and with fractions
432
+ in Python versions >= 3.2 (contributed by Case Vanhorsen)
433
+
434
+ Special functions:
435
+
436
+ * Implemented the von Mangoldt function (mangoldt())
437
+ * Implemented the "secondary zeta function" (secondzeta()) (contributed
438
+ by Juan Arias de Reyna).
439
+ * Implemented zeta zero counting (nzeros()) and the Backlund S function
440
+ (backlunds()) (contributed by Juan Arias de Reyna)
441
+ * Implemented derivatives of order 1-4 for siegelz() and siegeltheta()
442
+ (contributed by Juan Arias de Reyna)
443
+ * Improved Euler-Maclaurin summation for zeta() to give more accurate
444
+ results in the right half-plane when the reflection formula
445
+ cannot be used
446
+ * Implemented the Lerch transcendent (lerchphi())
447
+ * Fixed polygamma function to return a complex NaN at complex
448
+ infinity or NaN, instead of raising an unrelated exception.
449
+
450
+
451
+ --0.16--
452
+ Released September 24, 2010
453
+
454
+ Backends and distribution:
455
+
456
+ * Added Sage hooks for Cython versions of exp, ln, cos, sin,
457
+ hypergeometric series, and some related functions
458
+ * Fixed imports for gmpy2 compatibility (contributed by Case Van Horsen)
459
+ * Removed documentation from main mpmath package to save space (a separate
460
+ tar.gz file is now provided for the documentation sources)
461
+ * Fixed matplotlib version detection
462
+ * Converted files to Unix line endings
463
+
464
+ Special functions:
465
+
466
+ * Started adding plots of special functions to the documentation
467
+ * Added Anger and Weber functions (angerj(), webere())
468
+ * Added Lommel functions (lommels1(), lommels2())
469
+ * Added interval versions of gamma(), loggamma(), rgamma() and
470
+ factorial()
471
+ * Rewritten Airy functions to improve speed and accuracy
472
+ * Support for arbitrary-order derivatives of airyai(), airybi()
473
+ * Added Airy function zeros (airyaizero(), airybizero())
474
+ * Added Scorer functions (scorergi(), scorerhi())
475
+ * Added computation of Bessel function zeros and Bessel function
476
+ derivative zeros (besseljzero(), besselyzero())
477
+ * Fixed besselj(mpc(n), z)
478
+ * Rewritten lambertw() to fix various subtle bugs and robustly handle
479
+ numerical difficulties near branch cuts and branch points.
480
+ * Fixed fp.lambertw() to behave the same on branch cuts on systems with
481
+ and without signed-zero floats
482
+ * Added Carlson symmetric incomplete elliptic integrals
483
+ (elliprf(), elliprc(), elliprj(), elliprd(), elliprg())
484
+ * Added Legendre incomplete elliptic integrals (ellipf(), ellippi(),
485
+ ellipe() with two arguments)
486
+ * Implemented Parabolic cylinder functions (pcfd(), pcfu(), pcfv(),
487
+ pcfw())
488
+ * Implemented Euler-Maclaurin summation for hypergeometric functions
489
+ of order (p,p-1) to support evaluation with z close to 1 in remaining cases
490
+ * Fixed a bug in hypergeometric series summation, causing occasional
491
+ inaccurate results and incorrect detection of zeros
492
+ * Fixed qfrom(m=...)
493
+
494
+ Calculus:
495
+
496
+ * Implemented generators diffs_exp(), diffs_prod() for composing
497
+ derivatives
498
+ * Implemented Abel-Plana summation for infinite series (sumap())
499
+
500
+ Basic arithmetic and functions:
501
+
502
+ * Implemented matrix slice indexing, supporting submatrix
503
+ extraction and assignment (contributed by Ioannis Tziakos)
504
+ * Added missing constant fp.glaisher
505
+ * Fixed a bug preventing internal rational numbers from being
506
+ hashable
507
+ * Fixed bug in isnpint()
508
+ * Fixed a bug in cos_sin() for pure imaginary argument
509
+ * Slightly improved performance for elementary functions of pure
510
+ real or pure imaginary mpc inputs
511
+ * Fixed plot() with real-valued mpc instances
512
+ * Fixed cplot() to work with endpoints of other type than float/int
513
+
514
+
515
+ --0.15--
516
+ Released June 6, 2010
517
+
518
+ Basic transcendental functions:
519
+
520
+ * Reimplemented all elementary functions except log, reducing
521
+ overhead and giving asymptotic speedups at high precision
522
+ * Reimplemented gamma() and loggamma(), improving speed and
523
+ fixing accuracy in corner cases
524
+ * Added rgamma() (reciprocal gamma function)
525
+ * Added a stress test suite for the gamma function
526
+ * Provided top-level functions cos_sin() and cospi_sinpi() for fast
527
+ simultaneous computation
528
+
529
+ Riemann zeta function:
530
+
531
+ * New zetazeros() implementation, supporting arbitrarily large indices
532
+ (contributed by Juan Arias de Reyna)
533
+ * Tuned algorithm selection in zeta() for complex arguments
534
+ (contributed by Juan Arias de Reyna)
535
+ * Accelerated computation of zeta function series using sieving
536
+
537
+ Special functions:
538
+
539
+ * Added qfrom(), qbarfrom(), mfrom(), kfrom(), taufrom() for elliptic
540
+ argument conversion
541
+ * Merged jsn(), jcn(), jdn() -> ellipfun() and generalized it to compute
542
+ all 12 Jacobi elliptic functions
543
+ * Implemented the Klein j-invariant (kleinj())
544
+ * Implemented the q-Pochhammer symbol (qp())
545
+ * Implemented q-factorial (qfac()) and q--gamma (qgamma())
546
+ * Implemented q-hypergeometric series (qhyper())
547
+ * Implemented bilateral hypergeometric series (bihyper())
548
+ * Implemented Appell 2D hypergeometric series F2-F4 (appellf2()-appellf4())
549
+ * Implemented generalized 2D hypergeometric series (hyper2d())
550
+ * Fixed gammainc() for integer-valued complex argument (contributed by
551
+ Juan Arias de Reyna)
552
+ * Fixed asymptotic expansion of hyp1f1() (contributed by Juan Arias de Reyna)
553
+
554
+ Numerical calculus:
555
+
556
+ * Added support for multidimensional series in nsum()
557
+ * Made nprod() faster by default by extrapolating directly instead of
558
+ calling nsum()
559
+ * Changed some options for diff()/diffs()
560
+ * Made taylor() chop tiny coefficients by default
561
+ * Added support for partial derivatives in diff()
562
+
563
+ Interval arithmetic:
564
+
565
+ * All interval arithmetic functionality moved to a separate context
566
+ namespace (iv)
567
+ * Preliminary support for complex intervals (iv.mpc)
568
+ * Fixed interval cos/sin to support intervals overlapping zeros/extreme points
569
+ * Implemented interval atan2
570
+ * Implemented exp/log/cos/sin for complex intervals
571
+ * Some other interface changes to interval code
572
+
573
+ Utility functions:
574
+
575
+ * Made chop() use relative rather than absolute tolerance for
576
+ real/imaginary parts
577
+ * Optimized floor(), ceil(), isinf(), isnan(), isint()
578
+ * Implemented nint(), frac(), isnormal()
579
+ * Fixed and documented semantics for isinf(), isin(), isnan()
580
+ * Added utility functions autoprec(), maxcalls(), memoize()
581
+
582
+ Miscellaneous tweaks and fixes:
583
+
584
+ * Support complex conjugation in fdot()
585
+ * Added support for Cholesky decomposition of complex matrices
586
+ * Fixed a small precision bug in linear algebra functions
587
+ * Suppress NoConvergence exception when plotting
588
+ * Removed some dirty code to improve PyPy compatibility
589
+ * Fixed plotting to work with mpmath numbers in the interval specification
590
+ * Fixed fp arithmetic on systems where math.log and math.sqrt return NaN
591
+ instead of raising an exception
592
+ * Fixed fp.conj for Python 2.4 and 2.5
593
+ * Fixed quadrature to work with reversed infinite intervals such as [0,-inf]
594
+ * Renamed modf() -> fmod() for consistency
595
+
596
+ --0.14--
597
+ Released February 5, 2010
598
+
599
+ General changes:
600
+
601
+ * Fully separated the code into "low-level" and "high-level", permitting the
602
+ use of alternative contexts (the mpmath.mp object provides the default
603
+ implementation)
604
+ * Implemented a context for fast double-precision arithmetic using Python
605
+ types (mpmath.fp)
606
+ * Implemented hooks for importing a faster version of mp arithmetic from Sage
607
+ * Implemented optimized fp versions of certain functions (including erf, erfc,
608
+ gamma, digamma, ei, e1)
609
+ * Renamed and reorganized various internal modules and methods (including
610
+ merging low-level modules into mpmath.libmp). This should not affect most
611
+ external code using top-level imports.
612
+
613
+ Plotting:
614
+
615
+ * Implemented splot() for 3D surface plots (contributed by Jorn Baayen)
616
+ * Permit calling plot functions with custom axes (contributed by Jorn Baayen)
617
+
618
+ Matrices:
619
+
620
+ * Fixed lu_solve for overdetermined systems (contributed by Vinzent Steinberg)
621
+ * Added conjugate matrix transpose (contributed by Vinzent Steinberg)
622
+ * Implemented matrix functions (expm, cosm, sinm, sqrtm, logm, powm)
623
+
624
+ Miscellaneous:
625
+
626
+ * Prettier printing of numbers with leading zeros at small precisions
627
+ * Made nstr pass on kwargs, permitting more formatting options
628
+ * Fixed wrong directed rounding of addition of numbers with large magnitude
629
+ differences
630
+ * Fixed several docstring typos (contributed by Chris Smith)
631
+ * Fixed a bug that prevented caching of quadrature nodes to work optimally.
632
+
633
+ Special functions:
634
+
635
+ * Implemented fast evaluation for large imaginary heights of the Riemann zeta
636
+ function, Z function and derived functions using the Riemann-Siegel
637
+ (contributed by Juan Arias de Reyna)
638
+ * Unified the zeta() and hurwitz() functions, automatically selecting a fast
639
+ algorithm
640
+ * Improved altzeta() to fall back to zeta() for large arguments
641
+ * Fixed accuracy of zeta(s) for s ~= 1
642
+ * Implemented exact evaluation of Euler numbers (contributed by Juan Arias
643
+ de Reyna)
644
+ * Implemented numerical evaluation of Euler numbers and Euler polynomials
645
+ (eulernum(), eulerpoly())
646
+ * Fixed bernpoly() and eulerpoly() to compute accurate values for large
647
+ parameters
648
+ * Fixed accuracy problems for hypergeometric functions with large parameters
649
+ * Faster evaluation of hypergeometric series using on-the-fly code generation
650
+ * Optimized hypercomb to detect certain zero terms symbolically
651
+ * Removed the djtheta function (jtheta() accepts a derivative parameter)
652
+ * Implemented li(x, offset=True) to compute the offset logarithmic integral
653
+ * Fixed wrong branch in Lambert W function for certain complex inputs
654
+ * Implemented the reflection formula for the Barnes G-function,
655
+ superfactorials, hyperfactorials, permitting large arguments in the left
656
+ half-plane
657
+ * Implemented analytic continuation to |z| >= 1 for hypergeometric functions
658
+ pFq with p=q+1; added hyp3f2()
659
+ * Implemented Borel summation of divergent pFq functions with p > q+1
660
+ * Implemented automatic degree reduction of hypergeometric functions with
661
+ repeated parameters
662
+ * Added convenience functions expj(), expjpi()
663
+ * Use Mathematica's convention for the continuation of the Meijer G-function
664
+ * Added phase(), polar(), rect() functions for compatibility with the
665
+ Python 2.6 cmath module
666
+ * Implemented spherical harmonics (spherharm())
667
+ * Optimized ci(), si(), chi(), shi() for complex arguments by evaluating
668
+ them in terms of ei()
669
+ * Optimized hyp2f1 for z ~= -1
670
+
671
+ --0.13--
672
+ Released August 13, 2009
673
+
674
+ New special functions:
675
+
676
+ * The generalized exponential integral E_n (expint(), e1() for E_1)
677
+ * The generalized incomplete beta function (betainc())
678
+ * Whittaker functions (whitm(), whitw())
679
+ * Struve functions (struveh(), struvel())
680
+ * Kelvin functions (ber(), bei(), ker(), kei())
681
+ * Cyclotomic polynomials (cyclotomic())
682
+ * The Meijer G-function (meijerg())
683
+ * Clausen functions (clsin(), clcos())
684
+ * The Appell F1 hypergeometric function of two variables (appellf1())
685
+ * The Hurwitz zeta function, with nth order derivatives (hurwitz())
686
+ * Dirichlet L-series (dirichlet())
687
+ * Coulomb wave functions (coulombf(), coulombg(), coulombc())
688
+ * Associated Legendre functions of 1st and 2nd kind (legenp(), legenq())
689
+ * Hermite polynomials (hermite())
690
+ * Gegenbauer polynomials (gegenbauer())
691
+ * Associated Laguerre polynomials (laguerre())
692
+ * Hypergeometric functions hyp1f2(), hyp2f2(), hyp2f3(), hyp2f0(), hyperu()
693
+
694
+ Evaluation of hypergeometric functions:
695
+
696
+ * Added the function hypercomb() for evaluating expressions containing
697
+ hypergeometric series, with automatic handling of limits
698
+ * The available hypergeometric series (of orders up to and including 2F3)
699
+ implement asymptotic expansions with respect to the last argument z, allowing
700
+ fast and accurate evaluation anywhere in the complex plane. A massive number
701
+ of functions, including Bessel functions, error functions, etc., have been
702
+ updated to take advantage of this to support fast and accurate evaluation
703
+ anywhere in the complex plane.
704
+ * Fixed hyp2f1 to handle z close to and on the unit circle (supporting
705
+ evaluation anywhere in the complex plane)
706
+ * hyper() handles the 0F0 and 1F0 cases exactly
707
+ * hyper() eventually raises NoConvergence instead of getting stuck in
708
+ an infinite loop if given a divergent or extremely slowly convergent series
709
+
710
+ Other improvements and bug fixes to special functions:
711
+
712
+ * gammainc is much faster for large arguments and avoids catastrophic
713
+ cancellation
714
+ * Implemented specialized code for ei(x), e1(x), expint(n,x) and gammainc(n,x)
715
+ for small integers n, making evaluation much faster
716
+ * Extended the domain of polylog
717
+ * Fixed accuracy for asin(x) near x = 1
718
+ * Fast evaluation of Bernoulli polynomials for large z
719
+ * Fixed Jacobi polynomials to handle some poles
720
+ * Some Bessel functions support computing nth order derivatives
721
+ * A set of "torture tests" for special functions is available as
722
+ tests/torture.py
723
+
724
+ Other:
725
+ * Implemented the differint() function for fractional differentiaton / iterated
726
+ integration
727
+ * Added functions fadd, fsub, fneg, fmul, fdiv for high-level arithmetic with
728
+ controllable precision and rounding
729
+ * Added the function mag() for quick order-of-magnitude estimates of numbers
730
+ * Implemented powm1() for accurate calculation of x^y-1
731
+ * Improved speed and accuracy for raising a pure imaginary number to
732
+ an integer power
733
+ * nthroot() renamed to root(); root() optionally computes any of
734
+ the non-principal roots of a number
735
+ * Implemented unitroots() for generating all (primitive) roots of unity
736
+ * Added the mp.pretty option for nicer repr output
737
+
738
+ --0.12--
739
+ Released June 9, 2009
740
+
741
+ General
742
+ * It is now possible to create multiple context objects and use context-local
743
+ methods instead of global state/functions (e.g. mp2=mp.clone(); mp2.dps=50;
744
+ mp2.cos(3)). Not all functions have been converted to context methods, and
745
+ there are some bugs, so this feature is currently experimental.
746
+ * If mpmath is installed in Sage 4.0 or later, mpmath will now use sage.Integer
747
+ instead of Python long internally.
748
+ * Removed instances of old-style integer division from the codebase.
749
+ * runtests.py can be run with -coverage to generate coverage statistics.
750
+
751
+ Types and basic arithmetic
752
+
753
+ * Fixed comparison with -inf.
754
+ * Changed repr format of the mpi interval type to make eval(repr(x)) == x.
755
+ * Improved printing of intervals, with configurable output format (contributed
756
+ by Vinzent Steinberg based on code by Don Peterson).
757
+ * Intervals supported by mpmathify() and nstr() (contributed by Vinzent
758
+ Steinberg).
759
+ * mpc is now hashable.
760
+ * Added more formatting options to the internal function to_str.
761
+ * Faster pure-Python square root.
762
+ * Fix trailing whitespace giving wrong values in str->mpf conversion.
763
+
764
+ Calculus
765
+
766
+ * Fixed nsum() with Euler-Maclaurin summation which would previously
767
+ ignore the starting index and sum from n=1.
768
+ * Implemented Newton's method for findroot() (contributed by Vinzent
769
+ Steinberg).
770
+
771
+ Linear algebra
772
+
773
+ * Fixed LU_decomp() to recognize singular matrices (contributed by Jorn Baayen).
774
+ * The various norm functions were replaced by the generic vector norm
775
+ function norm(x,p) and the generic matrix norm function mnorm(x,p).
776
+
777
+ Special functions:
778
+
779
+ * Some internal caches were changed to always slightly overallocate
780
+ precision. This fixes worst-case behavior where previously the cached
781
+ value had to be recomputed on every function call.
782
+ * Fixed log(tiny number) returning nonsense at high precision.
783
+ * Fixed gamma() and derivative functions such as binomial() returning
784
+ wrong results at integer inputs being divisible by a large power of 2.
785
+ * Fixed asin() not to raise an exception at high precision (contributed
786
+ by Vinzent Steinberg).
787
+ * Optimized the AGM code for the natural logarithm, making the previously
788
+ used Newton method at intermediate precisions obsolete.
789
+ * The arithmetic-geometric mean function agm() is now an order of magnitude
790
+ faster at low precision.
791
+ * Faster implementations of ellipk() and ellipe().
792
+ * Analytic continuation of ellipe() to |x| >= 1 implemented.
793
+ * Implemented the log gamma function (loggamma()) with correct branch
794
+ cuts (slow, placeholder implementation).
795
+ * Fixed branch cuts of hyperfac().
796
+ * Implemented the Riemann-Siegel Z-function (siegelz()).
797
+ * Implemented the Riemann-Siegel theta function (siegeltheta()).
798
+ * Implemented calculation of Gram points (grampoint()).
799
+ * Implemented calculation of Riemann zeta function zeros (zetazero()).
800
+ * Implemented the prime counting function: a slow, exact version (primepi()).
801
+ and a fast approximate version (primepi2()) that gives a bounding interval.
802
+ * Implemented the Riemann R prime counting function (riemannr()).
803
+ * Implemented Bell numbers and polynomials (bell()).
804
+ * Implemented the expm1() function.
805
+ * Implemented the 'polyexponential function' (polyexp()).
806
+ * Implemented the twin prime constant (twinprime) and Mertens' constant
807
+ (mertens).
808
+ * Implemented the prime zeta function (primezeta()).
809
+
810
+
811
+ --0.11--
812
+ Released January 26, 2009
813
+
814
+ General:
815
+
816
+ * Most of the documentation is now generated from docstrings
817
+ using Sphinx' autodoc feature, and proper LaTeX is used
818
+ for mathematical formulas. A large amount of new documentation
819
+ has been written.
820
+ * Improved gmpy backend. Using gmpy-1.04 gives a ~30% unit tests
821
+ speedup over 1.03, with speedups in the range of 2-3x for
822
+ specific operations (contributed by Case van Horsen and
823
+ Mario Pernici).
824
+ * Mpmath imports slightly faster due to not trying to
825
+ load the 'random' library
826
+
827
+ Numerical calculus, etc:
828
+
829
+ * Implemented a fast high-precision ODE solver (to replace the slow
830
+ and low-accuracy RK4 algorithm) (odefun())
831
+ * Created an intelligent function nsum() to replace sumrich/sumsh
832
+ * Implemented nprod() for computing infinite products
833
+ * Rewrote limit() to use the same adaptive extrapolation algorithm
834
+ as nsum()
835
+ * Multidimensional nonlinear solving with Newton's method
836
+ implemented in findroot() (contributed by Vinzent Steinberg)
837
+ * Simplified the implementation and interface of sumem()
838
+ * Reimplemented Shanks transformation for nsum using Wynn's epsilon
839
+ algorithm (shanks())
840
+ * Reimplemented Richardson extrapolation slightly more simply and
841
+ efficiently (richardson())
842
+ * Prevent shanks() from exiting prematurely by adding
843
+ random noise to zeros
844
+ * Removed the obsolete secant() function (see findroot())
845
+ * Implemented high-order derivatives (diff(), diffs())
846
+ * Implemented calculation of Taylor series (taylor())
847
+ * Implemented calculation of Fourier series (fourier(), fourierval())
848
+ * Implemented Pade approximation (pade()) (contributed by
849
+ Mario Pernici)
850
+ * Better cancel condition for findroot() (contributed by
851
+ Vinzent Steinberg)
852
+ * Some refactoring of numerical integration code
853
+ * Fix erroneous nodes for 0-th order Gauss-Legendre quadrature,
854
+ which was causing unnecessary slowness
855
+ * Quadrature nodes are cached for arbitrary intervals, giving a
856
+ 30% speedup for repeated integrations
857
+ * Unified interface and added more options for identify(), pslq(), findpoly()
858
+
859
+ New special functions:
860
+
861
+ * Implemented polylogarithms (polylog())
862
+ * Implemented Bernoulli polynomials (bernpoly())
863
+ * Implemented the Barnes G-function (barnesg())
864
+ * Implemented double factorials (fac2())
865
+ * Implemented superfactorials (superfac())
866
+ * Implemented hyperfactorials (hyperfac())
867
+ * Replaced lower_gamma and upper_gamma with a more versatile
868
+ function gammainc() for computing the generalized (and optionally
869
+ regularized) incomplete gamma function
870
+ * Implemented sinc() and sincpi()
871
+ * Implemented Fibonacci numbers (fib())
872
+ * Implemented the Dirichlet eta function (altzeta())
873
+ * Implemented the inverse error function (erfinv())
874
+ * Jacobi theta functions and elliptic functions were essentially
875
+ rewritten from scratch, making them much faster and more
876
+ general. Renamed Jacobi theta functions: jacobi_theta -> jtheta,
877
+ etc. (contributed by Mario Pernici)
878
+ * Implemented derivatives of jtheta (djtheta) (contributed by
879
+ Mario Pernici)
880
+ * Implemented Bessel Y, I, K functions (bessely, besseli,
881
+ besselk; Bessel J functions were also renamed to besselj)
882
+ also renamed)
883
+ * Generalized Stieltjes constants can now be computed,
884
+ with stieltjes(n,a)
885
+ * Implemented Hankel functions (hankel1, hankel2)
886
+
887
+ Speed improvements and bugfixes to special functions:
888
+ * Fast logarithm at very high precision using the formula by
889
+ Sasaki and Kanada (contributed by Mario Pernici)
890
+ * Slightly faster logarithm at low precision (contributed by
891
+ Mario Pernici)
892
+ * Faster exponential function at high precision, using
893
+ Newton's method (contributed by Mario Pernici)
894
+ * Faster computation of ln2 and ln10 by means of binary splitting
895
+ (contributed by Mario Pernici)
896
+ * Fixed accuracy problems in sinpi() and cospi()
897
+ * Correct evaluation of beta() at limits
898
+ * Much faster evaluation of stieltjes(n), using an improved integral
899
+ formula
900
+ * Fixed bernoulli() being inaccurate for large n and low precision,
901
+ and being needlessly slow for small n and huge precision
902
+ * Fixed accuracy of zeta(s) for large negative re(s)
903
+ * Fixed accuracy problems for asinh, atanh and tanh
904
+ * Fixed accuracy of airyai() for large x.real
905
+ * Fixed bug in nthroot() for very large arguments (contributed by
906
+ Mario Pernici)
907
+ * Fixed accuracy of log(x) for complex |x| ~= 1
908
+ * Fixed accuracy of exp(n), n a huge integer and prec >= 600
909
+ * Slightly faster hypergeometric functions with rational parameters
910
+ (contributed by Mario Pernici)
911
+ * Faster and more accurate calculation of ci(x), si(x)
912
+ * Faster and more accurate calculation of ei(x) for large x,
913
+ using an asymptotic expansion (contributed by Mario Pernici)
914
+ * Fixed accuracy bugs in theta functions (contributed by
915
+ Mario Pernici)
916
+ * The Lambert W function returns more appropriate values at infinities
917
+
918
+ Arithmetic and basic interface:
919
+ * Square roots are now rounded correctly
920
+ * Made float(huge) -> inf and float(1/huge) -> 0 instead of
921
+ raising OverflowError
922
+ * Renamed convert_lossless -> mpmathify
923
+ * mpmathify() accepts strings representing fractions or complex
924
+ numbers (contributed by Vinzent Steinberg)
925
+ * Fixed a bug in interval multiplication giving wrong signs
926
+ * Added monitor() to monitor function evaluation
927
+ * Implemented a chop() utility function for deletion of numerical noise
928
+ * Added re(), im(), conj(), fabs(), mpf.conjugate()
929
+ * Fixed the != operator for intervals
930
+ * Added functions fsum, fprod, fdot for efficient computation of
931
+ sums, products and dot products of lists of mpf:s or mpc:s
932
+
933
+ Matrices:
934
+
935
+ * Generation of Hilbert matrices (hilbert()) (contributed by
936
+ Vinzent Steinberg)
937
+ * Added lu_solve_mat() to solve a*x=b where a and b are matrices (contributed
938
+ by Mario Pernici)
939
+ * Implemented computation of matrix exponentials (exp_pade()) (contributed
940
+ by Mario Pernici)
941
+ * Prettier repr of complex matrices (contributed by Vinzent Steinberg)
942
+ * Speedups by using fdot and fsum (contributed by Vinzent Steinberg)
943
+
944
+ --0.10--
945
+ Released October 15, 2008
946
+
947
+ Interface / general:
948
+ * Mpmath now works with Python 2.6
949
+ * Implemented function plotting via 'plot' and 'cplot' (requires
950
+ matplotlib)
951
+ * Removed global rounding mode (always rounding to nearest by default)
952
+ * Instead added 'prec', 'dps', 'rounding' keyword arguments to
953
+ standard functions, for optional fine-grained control over precision
954
+ and rounding
955
+ * Implemented isinf, isnan, isint, utility functions
956
+ * A large number of internal functions were moved and/or renamed to
957
+ improve consistency. This particularly affects low-level mpf
958
+ functions (lib.fadd -> libmpf.mpf_add, etc).
959
+ * Syntax for some operations was changed (see details below)
960
+ * The test runner (runtests.py) was updated to support running
961
+ isolated tests and to allow a local import of mpmath
962
+ * Unit tests can now be run with import mpmath; mpmath.runtests()
963
+ * Implicit imports are no longer used internally in the main codebase.
964
+ (This will hopefully make the source easier to read, and can catch
965
+ installation problems more cleanly.)
966
+
967
+ Added linear algebra functions (contributed by Vinzent Steinberg):
968
+ * Provided a matrix class
969
+ * Computation of powers, inverses, determinants
970
+ * Linear system solving using LU, QR and Cholesky
971
+ * Vector and matrix norms
972
+ * Calculation of condition numbers
973
+
974
+ Improvements to interval arithmetic:
975
+ * Fixed rounding direction for negative numbers and related
976
+ spurious bugs
977
+ * Fix interval exponentiation (all cases should work now)
978
+ * Basic interval arithmetic is up to 10x faster
979
+ * sqrt, exp, log, sin, cos and a few other functions
980
+ accept interval arguments
981
+ * Intervals supported in matrices
982
+
983
+ Changes to root-finding code:
984
+ * secant renamed to findroot
985
+ * findroot was made more general; many useful alternative root-finding
986
+ algorithms were implemented (contributed by Vinzent Steinberg)
987
+
988
+ Improvements to special functions:
989
+ * Implemented polygamma functions
990
+ * Implemented harmonic numbers
991
+ * Implemented Stieltjes constants
992
+ * Made gamma more accurate for huge arguments and/or precision
993
+ * Made zeta more accurate in various cases
994
+ * Made zeta typically 2-5x faster
995
+ * Much more efficient computation of zeta for huge s (zeta(s) ~= 1)
996
+ * Optimized numerical calculation of Bernoulli numbers
997
+ * Fast exact calculation of huge Bernoulli numbers via zeta and the
998
+ von Staudt-Clausen theorem
999
+ * Using AGM to compute ellipk, which is much faster and works
1000
+ in the entire complex plane
1001
+ * Allow single-argument form agm(x) = agm(1,x)
1002
+ * Faster and more accurate computation of erf
1003
+ * Added fast and accurate implementation of erfc
1004
+ * Normal probability functions npdf, ncdf
1005
+ * Fixed directed rounding in corner cases for various functions
1006
+
1007
+ Improvements to numerical integration:
1008
+ * Changed syntax for integration (quad(f, [a, b], options))
1009
+ * Implemented Gauss-Legendre quadrature
1010
+ * Direct support for triple integrals (quad(f, X, Y, Z))
1011
+ * Interval can be a list of several points, to split integration
1012
+ into subintervals
1013
+ * Oscillatory quadrature uses Gauss-Legendre instead of tanh-sinh,
1014
+ since this is typically faster
1015
+ * Fixed minor rounding bug in tanh-sinh quadrature not giving
1016
+ complete symmetry in the nodes
1017
+ * Implemented quadrature rules in classes for improved extensibility
1018
+
1019
+ Various speed improvements:
1020
+ * Up to 3x faster computation of log(x) at low precision, due to using
1021
+ Taylor series with argument reduction and partial caching
1022
+ * About 2x faster log(x) at very high precision due to more efficient
1023
+ computation of exp in the Newton iteration
1024
+ * Up to 10x faster computation of atan(x) at low to medium precision,
1025
+ due to using Taylor series with argument reduction and partial caching
1026
+ * Faster pickling due to using hex() instead of long()
1027
+ * Optimized code for Khinchin's constant (2.5x faster at 1000 digits)
1028
+ * Optimized code for Glaisher's constant (1.5x faster at 1000 digits)
1029
+ * Faster algorithm for Euler's constant (10x faster at 10000 digits)
1030
+ * Rewrote PSLQ to use fixed-point arithmetic, giving a ~7x speedup
1031
+ in pslq, findpoly and identify
1032
+
1033
+ Miscellaneous bugfixes:
1034
+ * Fixed nthroot for n = -1, 0, 1
1035
+ * Fixed inf/2**n and nan/2**n returning zero
1036
+
1037
+ --0.9--
1038
+ Released August 23, 2008
1039
+
1040
+ * gmpy mpzs are used instead of python ints when available, for
1041
+ huge speedups at high precision (contributed by Case Van Horsen)
1042
+ * using binary splitting to compute pi and e near-optimally
1043
+ * mpmath includes __version__ information
1044
+ * arange behaves more like range (contributed by Vinzent Steinberg)
1045
+ * asymptotically faster trigonometric functions via Brent's trick
1046
+ (contributed by Mario Pernici)
1047
+ * asymptotically faster inverse trigonometric functions via Newton's
1048
+ method (contributed by Mario Pernici)
1049
+ * added Jacobi elliptic functions 1-4, sn, cn, dn (contributed by Mike
1050
+ Taschuk)
1051
+ * polyval, polyroots and related functions now use the same order
1052
+ for coefficients as scipy and matlab (i.e. the reverse order of what
1053
+ was used previously in mpmath)
1054
+ * fixed polyroots for degree-0 polynomials (contributed by Nimish Telang)
1055
+ * added convenience functions (log10, degrees, radians, frexp, modf, ln,
1056
+ arg, sign)
1057
+ * added fast cbrt and nthroot functions for computing nth roots
1058
+ (contributed by (Mario Pernici)
1059
+ * added various exponential integrals (ei, li, si, ci, shi, chi, erfi)
1060
+ * added airy functions (airyai, airybi)
1061
+ * more __op__ and __rop__ methods return NotImplemented where
1062
+ appropriate
1063
+ * external classes can define a special method _mpmath_ to interact
1064
+ with mpmath numbers and functions
1065
+ * fixed some corner cases in atan2
1066
+ * faster rand()
1067
+
1068
+ --0.8--
1069
+ Released April 20, 2008
1070
+
1071
+ New features:
1072
+ * the full set of reciprocal trigonometric and hyperbolic functions
1073
+ and their inverses (cotangent, secant, etc) is available
1074
+ * oscillatory quadrature algorithm
1075
+ * the PSLQ algorithm and constant recognition functions
1076
+ * Richardson and Shanks transformations for computing limits and series
1077
+ * Euler-Maclaurin summation of series
1078
+ * basic ODE solvers (contributed by Ondrej Certik)
1079
+ * the Lambert W function
1080
+ * arithmetic-geometric mean function
1081
+ * generic hypergeometric series and some special hypergeometric
1082
+ functions (elliptic integrals, orthogonal polynomials)
1083
+ * several more mathematical constants
1084
+ * fast sequential computation of integer logarithms and Bernoulli
1085
+ numbers
1086
+ * Bessel function jv works for complex arguments and noninteger v
1087
+ * support for trapping complex results
1088
+ * using Sphinx to generate HTML documentation
1089
+
1090
+ Bugfixes, speed enhancements, and other improvements:
1091
+ * compatibility tests should now pass on systems where Python is
1092
+ compiled to use 80-bit registers for floating-point operations
1093
+ * fixed mpmath to work with some versions of Python 2.4 where a
1094
+ list indexing bug is present in the Python core
1095
+ * better algorithms for various complex elementary functions
1096
+ (tan and tanh by Fredrik; sqrt, acos, asin, acosh and asinh
1097
+ improved by Mario Pernici)
1098
+ * multiplication and integer powers for complex numbers is faster
1099
+ and more accurate
1100
+ * miscellaneous speed improvements to complex arithmetic (contributed
1101
+ by Mario Pernici)
1102
+ * faster computation of cos and sin when only one of them is needed
1103
+ (contributed by Mario Pernici)
1104
+ * slightly faster square roots at low precision (contributed by
1105
+ Mario Pernici)
1106
+ * fixed computation of exp(n) for negative integers and x**y for
1107
+ negative half integers y
1108
+ * mpf ** complex now works
1109
+ * faster generation of quadrature nodes (contributed by Mario Pernici)
1110
+ * faster change of variables for quadrature
1111
+ * comparisons and conversions have been optimized slightly.
1112
+ comparisons with float(nan) also work as intended.
1113
+ * str() is several times faster at very high precision
1114
+ * implementations of most elementary functions moved to the lib
1115
+ and libmpc modules for cleaner separation of functionality
1116
+ * the rounding argument for lib and libmpc functions, and for
1117
+ some functions also the the prec argument, are now optional,
1118
+ resulting in cleaner and slightly faster lib code
1119
+ * gamma and factorial are about 2x faster
1120
+ * polyroots returns nicer results
1121
+ * pickling now works for mpf and mpc instances
1122
+
1123
+ --0.7--
1124
+ Released March 12, 2008
1125
+
1126
+ * the interface for switching precision and rounding modes has been
1127
+ changed. instead of changing mpf.prec, there is a new object mp
1128
+ which holds the precision as mp.prec. this change improves
1129
+ flexibility in the implementation. it will unfortunately break
1130
+ any existing code written for mpmath, but the broken code should
1131
+ be trivial to update.
1132
+ * the functions workprec, workdps, extraprec, extradps have been
1133
+ introduced for switching precision in a more safe manner,
1134
+ ensuring that the precision gets reset when finished. they can
1135
+ be used with the 'with' statement available in python 2.5
1136
+ * improved documentation (manual.html)
1137
+ * the round-half-down and round-half-up modes have been deprecated,
1138
+ since they added complexity without being particularly useful.
1139
+ round-half-even has been renamed to round-nearest.
1140
+ * implemented the functions nstr, nprint for printing numbers with
1141
+ a small or custom number of digits
1142
+ * accuracy of cos and sin near roots has been fixed. computing
1143
+ sin(x) or cos(x) where x is huge is also much faster
1144
+ * implemented a magical constant eps that gives the "machine"
1145
+ epsilon
1146
+ * additional mathematical functions: implemented Catalan's constant
1147
+ and Bessel functions J_n(x) for integer n and real x
1148
+ * new functions diff and diffc for numerical differentiation
1149
+ * implemented the ldexp function for fast multiplication by 2**n
1150
+ * mpf uses rich comparison methods (contributed by Pearu Peterson)
1151
+ * epydoc-friendly docstrings (contributed by Pearu Peterson)
1152
+ * support creating mpf from float nan or inf
1153
+ * fixed printing of complex numbers with negative imaginary part
1154
+ * flattened package structure to simplify inclusion of mpmath in other
1155
+ packages
1156
+ * external classes can interoperate with mpf and mpc instances
1157
+ by defining _mpf_ or _mpc_ properties
1158
+ * renamed lib.fpow -> lib.fpowi and implemented lib.fpow for general
1159
+ real powers. <mpf> ** <mpf> should now be slightly faster and more
1160
+ robust
1161
+ * the internal number representation has been changed to include
1162
+ an explicit sign bit. as a result of this change and other small
1163
+ tweaks, arithmetic is up to 20% faster and the total running
1164
+ time for mpmath's unit tests has dropped 10%.
1165
+ * miscellaneous speed improvements:
1166
+ * <mpf> ** <int> is 2-3 times faster (contributed by Mario Pernici)
1167
+ * <mpf> * <int> and <int> * <mpf> is roughly twice as fast
1168
+ * <int> / <mpf> is roughly twice as fast (contributed by Mario
1169
+ Pernici)
1170
+ * exp and log are about 10% faster
1171
+ * fast computation of e and exp(n) when precision is extremely high
1172
+
1173
+ --0.6--
1174
+ Released January 13, 2008
1175
+
1176
+ * added the mpi type for interval arithmetic
1177
+ * powers with integer exponents are computed with directed rounding
1178
+ all the way through to preserve interval bounds more robustly
1179
+ (however, the code is not fully tested and may have some bugs)
1180
+ * string input to mpf.__new__() can now be unicode
1181
+ * mpf.__eq__ now works in pypy
1182
+ * infs and nans are now implemented in mpmath.lib, resulting in
1183
+ considerable simplification of the mpf class implementation
1184
+ * partial support for infs and nans in functions, e.g.
1185
+ exp(inf) -> inf and exp(-inf) -> 0 now work.
1186
+ * renamed several files. created mpmath.apps and moved tests into
1187
+ the main mpmath directory
1188
+ * wrote script to permit running unit tests without py.test available
1189
+ * improved bit counting code in fadd, fmul and fdiv, plus other
1190
+ small performance tweaks, resulting in a 20-30% speedup for
1191
+ arithmetic
1192
+
1193
+ --0.5--
1194
+ Released November 24, 2007
1195
+
1196
+ * added the quad module for arbitrary-precision numerical integration
1197
+ * floor and ceil functions available
1198
+ * implemented __mod__ and __rmod__ for the mpf class
1199
+ * partial support for the special numbers +inf, -inf and nan
1200
+ * faster multiplication and division (up to 40% faster with psyco)
1201
+ * simplified syntax for conversion function (from_int instead of
1202
+ from_int_exact, etc)
1203
+ * renamed cgamma to euler
1204
+ * more documentation strings
1205
+
1206
+ --0.4--
1207
+ Released November 3, 2007
1208
+
1209
+ * new string conversion code (much faster; unlimited exponents)
1210
+ * fixed bug in factorial (it gave the wrong value, though gamma worked)
1211
+ * division now uses a rigorous algorithm for directed rounding
1212
+ (mpmath previously used a heuristic that got the last bit wrong
1213
+ in 1/10000 of cases)
1214
+ * misc. performance improvements (arithmetic is 15% faster)
1215
+ * refactored parts of the code; added many more docstrings and tests
1216
+ * added a function rand() for generating full-precision random numbers
1217
+ * rewrote the benchmark script to compare against Decimal and to
1218
+ automatically generate timings with psyco both disabled and enabled
1219
+ * rewrote unit tests to use py.test
1220
+
1221
+ --0.3--
1222
+ Released October 5, 2007
1223
+
1224
+ * fixed high-precision accuracy problem in complex sqrt
1225
+ * fixed high-precision accuracy problem in atan and complex log
1226
+ * fixed directed rounding for sqrt (always rounded to nearest)
1227
+ * implemented all hyperbolic and inverse functions (there are some
1228
+ accuracy issues left to sort out)
1229
+ * included gamma, factorial, erf, zeta incomplete gamma functions
1230
+ * made sin and tan more accurate for complex input very close to 0
1231
+ * more docstrings
1232
+ * many more tests
1233
+ * including a benchmark script
1234
+
1235
+ -- 0.2 --
1236
+ Released October 2, 2007
1237
+
1238
+ * 50% faster exponential function
1239
+ * faster mpf <-> int ops
1240
+ * fixed import error in pidigits.py; added demos to source distribution
1241
+ * __rmul__ was missing on mpf
1242
+ * fixed bitcount bug also for -(2**n-1)
1243
+ * more docstrings
1244
+ * more tests; tests included in source distribution
1245
+ * approximate equality testing (.ae method) supported
1246
+ * implemented atan and atan2 functions
1247
+ * tan works for both mpfs and mpcs
1248
+ * complex logarithms and complex powers supported
1249
+ * more details in README
1250
+
1251
+ -- 0.1 --
1252
+ Released September 27, 2007
1253
+
1254
+ * imported code from SymPy's numerics module
1255
+ * renamed functions and restructured various parts of the code
1256
+ * fixed erroneous bitcount for 2**n-1 mantissa with directed rounding
1257
+ * various small speed improvements and bug fixes
mpmath/source/CITATION.bib ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ @manual{mpmath,
2
+ key = {mpmath},
3
+ author = {The mpmath development team},
4
+ title = {mpmath: a {P}ython library for arbitrary-precision floating-point arithmetic (version 1.4.0)},
5
+ note = {{\tt https://mpmath.org/}},
6
+ year = {2026},
7
+ }
mpmath/source/LICENSE ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2005-2026 Fredrik Johansson and mpmath contributors
2
+
3
+ All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ a. Redistributions of source code must retain the above copyright notice,
9
+ this list of conditions and the following disclaimer.
10
+ b. Redistributions in binary form must reproduce the above copyright
11
+ notice, this list of conditions and the following disclaimer in the
12
+ documentation and/or other materials provided with the distribution.
13
+ c. Neither the name of the copyright holder nor the names of its
14
+ contributors may be used to endorse or promote products derived
15
+ from this software without specific prior written permission.
16
+
17
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20
+ ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR
21
+ ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
23
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
24
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25
+ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26
+ OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
27
+ DAMAGE.
mpmath/source/README.rst ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ mpmath
2
+ ======
3
+
4
+ |pypi version| |Build status| |Zenodo Badge|
5
+
6
+ .. |pypi version| image:: https://img.shields.io/pypi/v/mpmath.svg
7
+ :target: https://pypi.python.org/pypi/mpmath
8
+ .. |Build status| image:: https://github.com/mpmath/mpmath/workflows/test/badge.svg
9
+ :target: https://github.com/mpmath/mpmath/actions?workflow=test
10
+ .. |Zenodo Badge| image:: https://zenodo.org/badge/2934512.svg
11
+ :target: https://zenodo.org/badge/latestdoi/2934512
12
+
13
+ A Python library for arbitrary-precision floating-point arithmetic.
14
+
15
+ Website: https://mpmath.org/
16
+ Main author: Fredrik Johansson <fredrik.johansson@gmail.com>
17
+
18
+ Mpmath is free software released under the New BSD License (see the
19
+ LICENSE file for details).
20
+
21
+ 0. History and credits
22
+ ----------------------
23
+
24
+ The following people (among others) have contributed major patches
25
+ or new features to mpmath:
26
+
27
+ * Pearu Peterson <pearu.peterson@gmail.com>
28
+ * Mario Pernici <mario.pernici@mi.infn.it>
29
+ * Ondrej Certik <ondrej@certik.cz>
30
+ * Vinzent Steinberg <vinzent.steinberg@gmail.com>
31
+ * Nimish Telang <ntelang@gmail.com>
32
+ * Mike Taschuk <mtaschuk@ece.ualberta.ca>
33
+ * Case Van Horsen <casevh@gmail.com>
34
+ * Jorn Baayen <jorn.baayen@gmail.com>
35
+ * Chris Smith <smichr@gmail.com>
36
+ * Juan Arias de Reyna <arias@us.es>
37
+ * Ioannis Tziakos <itziakos@gmail.com>
38
+ * Aaron Meurer <asmeurer@gmail.com>
39
+ * Stefan Krastanov <krastanov.stefan@gmail.com>
40
+ * Ken Allen <ken.allen@sbcglobal.net>
41
+ * Timo Hartmann <thartmann15@gmail.com>
42
+ * Sergey B Kirpichev <skirpichev@gmail.com>
43
+ * Kris Kuhlman <kristopher.kuhlman@gmail.com>
44
+ * Paul Masson <paulmasson@analyticphysics.com>
45
+ * Michael Kagalenko <michael.kagalenko@gmail.com>
46
+ * Jonathan Warner <warnerjon12@gmail.com>
47
+ * Max Gaukler <max.gaukler@fau.de>
48
+ * Guillermo Navas-Palencia <g.navas.palencia@gmail.com>
49
+ * Nike Dattani <nike@hpqc.org>
50
+ * Tim Peters <tim.peters@gmail.com>
51
+ * Javier Garcia <javier.garcia.tw@hotmail.com>
52
+
53
+ Numerous other people have contributed by reporting bugs,
54
+ requesting new features, or suggesting improvements to the
55
+ documentation.
56
+
57
+ For a detailed changelog, including individual contributions,
58
+ see the CHANGES file.
59
+
60
+ Fredrik's work on mpmath during summer 2008 was sponsored by Google
61
+ as part of the Google Summer of Code program.
62
+
63
+ Fredrik's work on mpmath during summer 2009 was sponsored by the
64
+ American Institute of Mathematics under the support of the National Science
65
+ Foundation Grant No. 0757627 (FRG: L-functions and Modular Forms).
66
+
67
+ Any opinions, findings, and conclusions or recommendations expressed in this
68
+ material are those of the author(s) and do not necessarily reflect the
69
+ views of the sponsors.
70
+
71
+ Credit also goes to:
72
+
73
+ * The authors of the GMP library and the Python wrapper
74
+ gmpy, enabling mpmath to become much faster at
75
+ high precision
76
+ * The authors of MPFR, pari/gp, MPFUN, and other arbitrary-
77
+ precision libraries, whose documentation has been helpful
78
+ for implementing many of the algorithms in mpmath
79
+ * Wikipedia contributors; Abramowitz & Stegun; Gradshteyn & Ryzhik;
80
+ Wolfram Research for MathWorld and the Wolfram Functions site.
81
+ These are the main references used for special functions
82
+ implementations.
83
+ * George Brandl for developing the Sphinx documentation tool
84
+ used to build mpmath's documentation
85
+
86
+ Release history:
87
+
88
+ * Version 1.4.0 released on February 23, 2026
89
+ * Version 1.3.0 released on March 7, 2023
90
+ * Version 1.2.1 released on February 9, 2021
91
+ * Version 1.2.0 released on February 1, 2021
92
+ * Version 1.1.0 released on December 11, 2018
93
+ * Version 1.0.0 released on September 27, 2017
94
+ * Version 0.19 released on June 10, 2014
95
+ * Version 0.18 released on December 31, 2013
96
+ * Version 0.17 released on February 1, 2011
97
+ * Version 0.16 released on September 24, 2010
98
+ * Version 0.15 released on June 6, 2010
99
+ * Version 0.14 released on February 5, 2010
100
+ * Version 0.13 released on August 13, 2009
101
+ * Version 0.12 released on June 9, 2009
102
+ * Version 0.11 released on January 26, 2009
103
+ * Version 0.10 released on October 15, 2008
104
+ * Version 0.9 released on August 23, 2008
105
+ * Version 0.8 released on April 20, 2008
106
+ * Version 0.7 released on March 12, 2008
107
+ * Version 0.6 released on January 13, 2008
108
+ * Version 0.5 released on November 24, 2007
109
+ * Version 0.4 released on November 3, 2007
110
+ * Version 0.3 released on October 5, 2007
111
+ * Version 0.2 released on October 2, 2007
112
+ * Version 0.1 released on September 27, 2007
113
+
114
+ 1. Download & installation
115
+ --------------------------
116
+
117
+ Mpmath requires Python 3.10 or later versions. It has been tested with CPython
118
+ 3.10 through 3.14 and for PyPy 3.11.
119
+
120
+ The latest release of mpmath can be downloaded from the mpmath
121
+ website and from https://github.com/mpmath/mpmath/releases
122
+
123
+ It should also be available in the Python Package Index at
124
+ https://pypi.python.org/pypi/mpmath
125
+
126
+ To install latest release of Mpmath with pip, simply run
127
+
128
+ ``pip install mpmath``
129
+
130
+ or from the source tree
131
+
132
+ ``pip install .``
133
+
134
+ The latest development code is available from
135
+ https://github.com/mpmath/mpmath
136
+
137
+ See the main documentation for more detailed instructions.
138
+
139
+ 2. Documentation
140
+ ----------------
141
+
142
+ Documentation in reStructuredText format is available in the
143
+ docs directory included with the source package. These files
144
+ are human-readable, but can be compiled to prettier HTML using
145
+ `Sphinx <https://www.sphinx-doc.org/>`_.
146
+
147
+ The most recent documentation is also available in HTML format:
148
+
149
+ https://mpmath.readthedocs.io/
150
+
151
+ 3. Running tests
152
+ ----------------
153
+
154
+ The unit tests in mpmath/tests/ can be run with `pytest
155
+ <https://pytest.org/>`_, see the main documentation.
156
+
157
+ You may also want to check out the demo scripts in the demo
158
+ directory.
159
+
160
+ The master branch is automatically tested on the Github Actions.
161
+
162
+ 4. Known problems
163
+ -----------------
164
+
165
+ Mpmath is a work in progress. Major issues include:
166
+
167
+ * Some functions may return incorrect values when given extremely
168
+ large arguments or arguments very close to singularities.
169
+
170
+ * Directed rounding works for arithmetic operations. It is implemented
171
+ heuristically for other operations, and their results may be off by one
172
+ or two units in the last place (even if otherwise accurate).
173
+
174
+ * Some IEEE 754 features are not available. Inifinities and NaN are
175
+ partially supported, there is no signed zero; denormal rounding is
176
+ not available at all.
177
+
178
+ * The interface for switching precision and rounding is not finalized.
179
+ The current method is not threadsafe.
180
+
181
+ 5. Help and bug reports
182
+ -----------------------
183
+
184
+ General questions and comments can be `sent <mailto:mpmath@googlegroups.com>`_
185
+ to the `mpmath mailinglist <https://groups.google.com/g/mpmath>`_.
186
+
187
+ You can also report bugs and send patches to the mpmath issue tracker,
188
+ https://github.com/mpmath/mpmath/issues
mpmath/source/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ """
3
+ mpmath Project Package Initialization File
4
+ """
mpmath/source/conftest.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+
3
+ import pytest
4
+
5
+ import mpmath
6
+
7
+
8
+ def pytest_report_header(config):
9
+ print("mpmath backend: %s" % mpmath.libmp.backend.BACKEND)
10
+ print("mpmath mp class: %s" % repr(mpmath.mp))
11
+ print("mpmath version: %s" % mpmath.__version__)
12
+ print("Python version: %s" % sys.version)
13
+
14
+
15
+ def pytest_configure(config):
16
+ config.addinivalue_line('markers', 'slow: marks tests as slow')
17
+
18
+
19
+ @pytest.fixture(autouse=True)
20
+ def reset_mp_globals():
21
+ mpmath.mp.prec = sys.float_info.mant_dig
22
+ mpmath.mp.pretty = False
23
+ mpmath.mp.rounding = 'n'
24
+ mpmath.mp.pretty_dps = "str"
25
+ mpmath.iv.prec = mpmath.mp.prec
26
+ mpmath.iv.pretty = False
mpmath/source/demo/mandelbrot.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This script uses the cplot function in mpmath to plot the Mandelbrot set.
3
+ By default, the fp context is used for speed. The mp context could be used
4
+ to improve accuracy at extremely high zoom levels.
5
+ """
6
+
7
+ import mpmath
8
+
9
+ ctx = mpmath.fp
10
+ # ctx = mpmath.mp
11
+
12
+ ITERATIONS = 50
13
+ POINTS = 100000
14
+ ESCAPE_RADIUS = 8
15
+
16
+ # Full plot
17
+ RE = [-2.5, 1.5]
18
+ IM = [-1.5, 1.5]
19
+
20
+ # A pretty subplot
21
+ #RE = [-0.96, -0.80]
22
+ #IM = [-0.35, -0.2]
23
+
24
+ def mandelbrot(z):
25
+ c = z
26
+ for i in range(ITERATIONS):
27
+ zprev = z
28
+ z = z*z + c
29
+ if abs(z) > ESCAPE_RADIUS:
30
+ return ctx.exp(1j*(i + 1 - ctx.log(ctx.log(abs(z)))/ctx.log(2)))
31
+ return 0
32
+
33
+ ctx.cplot(mandelbrot, RE, IM, points=POINTS, verbose=1)
mpmath/source/demo/manydigits.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This script calculates solutions to some of the problems from the
3
+ "Many Digits" competition:
4
+ http://www.cs.ru.nl/~milad/manydigits/problems.php
5
+
6
+ Run with:
7
+
8
+ python manydigits.py
9
+
10
+ """
11
+ from mpmath import (mp, sin, tan, cos, sqrt, e, pi, exp, atanh, mpf, tanh,
12
+ zeta, catalan, findroot, quadts, atan, asin, asinh)
13
+ from mpmath.libmp import to_fixed, bin_to_radix
14
+
15
+ dps = 100
16
+ mp.dps = dps + 10
17
+
18
+ def pr(x):
19
+ """Return the first dps digits after the decimal point"""
20
+ x = x._mpf_
21
+ p = int(dps*3.33 + 10)
22
+ t = to_fixed(x, p)
23
+ d = bin_to_radix(t, p, 10, dps)
24
+ s = str(d).zfill(dps)[-dps:]
25
+ return s[:dps//2] + "\n" + s[dps//2:]
26
+
27
+ print("""
28
+ This script prints answers to a selection of the "Many Digits"
29
+ competition problems: http://www.cs.ru.nl/~milad/manydigits/problems.php
30
+
31
+ The output for each problem is the first 100 digits after the
32
+ decimal point in the result.
33
+ """)
34
+
35
+ print("C01: sin(tan(cos(1)))")
36
+ print(pr(sin(tan(cos(1)))))
37
+ print()
38
+
39
+ print("C02: sqrt(e/pi)")
40
+ print(pr(sqrt(e/pi)))
41
+ print()
42
+
43
+ print("C03: sin((e+1)^3)")
44
+ print(pr(sin((e+1)**3)))
45
+ print()
46
+
47
+ print("C04: exp(pi*sqrt(2011))")
48
+ mp.dps += 65
49
+ print(pr(exp(pi*sqrt(2011))))
50
+ mp.dps -= 65
51
+ print()
52
+
53
+ print("C05: exp(exp(exp(1/2)))")
54
+ print(pr(exp(exp(exp(0.5)))))
55
+ print()
56
+
57
+ print("C06: arctanh(1-arctanh(1-arctanh(1-arctanh(1/pi))))")
58
+ print(pr(atanh(1-atanh(1-atanh(1-atanh(1/pi))))))
59
+ print()
60
+
61
+ print("C07: pi^1000")
62
+ mp.dps += 505
63
+ print(pr(pi**1000))
64
+ mp.dps -= 505
65
+ print()
66
+
67
+ print("C08: sin(6^(6^6))")
68
+ print(pr(sin(6**(6**6))))
69
+ print()
70
+
71
+ print("C09: sin(10*arctan(tanh(pi*(2011^(1/2))/3)))")
72
+ mp.dps += 150
73
+ print(pr(sin(10*atan(tanh(pi*sqrt(2011)/3)))))
74
+ mp.dps -= 150
75
+ print()
76
+
77
+ print("C10: (7+2^(1/5)-5*(8^(1/5)))^(1/3) + 4^(1/5)-2^(1/5)")
78
+ a = mpf(1)/5
79
+ print(pr(((7 + 2**a - 5*(8**a))**(mpf(1)/3) + 4**a - 2**a)))
80
+ print()
81
+
82
+ print("C11: tan(2^(1/2))+arctanh(sin(1))")
83
+ print(pr((tan(sqrt(2)) + atanh(sin(1)))))
84
+ print()
85
+
86
+ print("C12: arcsin(1/e^2) + arcsinh(e^2)")
87
+ print(pr(asin(1/exp(2)) + asinh(exp(2))))
88
+ print()
89
+
90
+ print("C17: S= -4*Zeta(2) - 2*Zeta(3) + 4*Zeta(2)*Zeta(3) + 2*Zeta(5)")
91
+ print(pr(-4*zeta(2) - 2*zeta(3) + 4*zeta(2)*zeta(3) + 2*zeta(5)))
92
+ print()
93
+
94
+ print(r"C18: Catalan G = Sum{i=0}{\infty}(-1)^i/(2i+1)^2")
95
+ print(pr(catalan))
96
+ print()
97
+
98
+ print("C21: Equation exp(cos(x)) = x")
99
+ print(pr(findroot(lambda x: exp(cos(x))-x, 1)))
100
+ print()
101
+
102
+ print("C22: J = integral(sin(sin(sin(x)))), x=0..1")
103
+ print(pr(quadts(lambda x: sin(sin(sin(x))), [0, 1])))
104
+ print()
mpmath/source/demo/pidigits.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Calculate digits of pi. This module can be run interactively with
3
+
4
+ python pidigits.py
5
+
6
+ """
7
+
8
+ import sys
9
+ import math
10
+ from time import perf_counter
11
+
12
+ from mpmath.libmp import bin_to_radix, numeral, pi_fixed
13
+
14
+ def display_fraction(digits, skip=0, colwidth=10, columns=5):
15
+ perline = colwidth * columns
16
+ printed = 0
17
+ for linecount in range((len(digits)-skip) // (colwidth * columns)):
18
+ line = digits[skip+linecount*perline:skip+(linecount+1)*perline]
19
+ for i in range(columns):
20
+ print(line[i*colwidth : (i+1)*colwidth], end=' ')
21
+ print(":", (linecount+1)*perline)
22
+ if (linecount+1) % 10 == 0:
23
+ print()
24
+ printed += colwidth*columns
25
+ rem = (len(digits)-skip) % (colwidth * columns)
26
+ if rem:
27
+ buf = digits[-rem:]
28
+ s = ""
29
+ for i in range(columns):
30
+ s += buf[:colwidth].ljust(colwidth+1, " ")
31
+ buf = buf[colwidth:]
32
+ print(s + ":", printed + colwidth*columns)
33
+
34
+ def calculateit(base, n, tofile):
35
+ intpart = numeral(3, base)
36
+ skip = 1
37
+ if base <= 3:
38
+ skip = 2
39
+
40
+ prec = int(n*math.log(base,2))+10
41
+
42
+ print("Step 1 of 2: calculating binary value...")
43
+ t = perf_counter()
44
+ a = pi_fixed(prec, verbose=True, verbose_base=base)
45
+ step1_time = perf_counter() - t
46
+
47
+ print("Step 2 of 2: converting to specified base...")
48
+ t = perf_counter()
49
+ d = bin_to_radix(a, prec, base, n)
50
+ d = numeral(d, base, n)
51
+ step2_time = perf_counter() - t
52
+
53
+ print("\nWriting output...\n")
54
+
55
+ if tofile:
56
+ out_ = sys.stdout
57
+ sys.stdout = tofile
58
+ print("%i base-%i digits of pi:\n" % (n, base))
59
+ print(intpart, ".\n")
60
+
61
+ display_fraction(d, skip, colwidth=10, columns=5)
62
+ if tofile:
63
+ sys.stdout = out_
64
+ print("\nFinished in %f seconds (%f calc, %f convert)" % \
65
+ ((step1_time + step2_time), step1_time, step2_time))
66
+
67
+ def interactive():
68
+ print("Compute digits of pi with mpmath\n")
69
+ base = input("Which base? (2-36, 10 for decimal) \n> ")
70
+ digits = input("How many digits? (enter a big number, say, 10000)\n> ")
71
+ tofile = input("Output to file? (enter a filename, or just press " \
72
+ "enter\nto print directly to the screen) \n> ")
73
+ if tofile:
74
+ tofile = open(tofile, "w")
75
+
76
+ calculateit(int(base), int(digits), tofile)
77
+ input("\nPress enter to close this script.")
78
+
79
+ if __name__ == "__main__":
80
+ interactive()
mpmath/source/demo/plotting.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Function plotting demo.
3
+ """
4
+ from mpmath import *
5
+
6
+ def main():
7
+ print("""
8
+ Simple function plotting. You can enter one or several
9
+ formulas, in ordinary Python syntax and using the mpmath
10
+ function library. The variable is 'x'. So for example
11
+ the input "sin(x/2)" (without quotation marks) defines
12
+ a valid function.
13
+ """)
14
+ functions = []
15
+ for i in range(10):
16
+ if i == 0:
17
+ s = input('Enter a function: ')
18
+ else:
19
+ s = input('Enter another function (optional): ')
20
+ if not s:
21
+ print()
22
+ break
23
+ f = eval("lambda x: " + s)
24
+ functions.append(f)
25
+ print("Added f(x) = " + s)
26
+ print()
27
+ xlim = input('Enter xmin, xmax (optional): ')
28
+ if xlim:
29
+ xlim = eval(xlim)
30
+ else:
31
+ xlim = [-5, 5]
32
+ print("Plotting...")
33
+ plot(functions, xlim=xlim)
34
+
35
+ main()
mpmath/source/demo/sofa.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ '''
2
+ This script calculates the constant in Gerver's solution to the moving sofa
3
+ problem.
4
+
5
+ See Finch, S. R. "Moving Sofa Constant." §8.12 in Mathematical Constants.
6
+ Cambridge, England: Cambridge University Press, pp. 519-523, 2003.
7
+ '''
8
+
9
+ from mpmath import cos, sin, pi, quad, findroot, mp
10
+
11
+ mp.prec = 113
12
+
13
+ eqs = [lambda A, B, φ, θ: (A*(cos(θ) - cos(φ)) - 2*B*sin(φ)
14
+ + (θ - φ - 1)*cos(θ) - sin(θ) + cos(φ) + sin(φ)),
15
+ lambda A, B, φ, θ: (A*(3*sin(θ) + sin(φ)) - 2*B*cos(φ)
16
+ + 3*(θ - φ - 1)*sin(θ) + 3*cos(θ) - sin(φ) + cos(φ)),
17
+ lambda A, B, φ, θ: A*cos(φ) - (sin(φ) + 0.5 - 0.5*cos(φ) + B*sin(φ)),
18
+ lambda A, B, φ, θ: ((A + pi/2 - φ - θ) - (B - (θ - φ)*(1 + A)/2
19
+ - 0.25*(θ - φ)**2))]
20
+ A, B, φ, θ = findroot(eqs, (0, 0, 0, 0))
21
+
22
+ def r(α):
23
+ if 0 <= α < φ:
24
+ return 0.5
25
+ if φ <= α < θ:
26
+ return (1 + A + α - φ)/2
27
+ if θ <= α < pi/2 - θ:
28
+ return A + α - φ
29
+ return B - (pi/2 - α - φ)*(1 + A)/2 - (pi/2 - α - φ)**2/4
30
+
31
+ s = lambda α: 1 - r(α)
32
+
33
+ def u(α):
34
+ if φ <= α < θ:
35
+ return B - (α - φ)*(1 + A)/2 - (α - φ)**2/4
36
+ return A + pi/2 - φ - α
37
+
38
+ def du(α):
39
+ if φ <= α < θ:
40
+ return -(1 + A)/2 - (α - φ)/2
41
+ return -1
42
+
43
+ def y(α, f):
44
+ if α > pi/2 - θ:
45
+ i = [0, φ, θ, pi/2 - θ, α]
46
+ elif α > θ:
47
+ i = [0, φ, θ, α]
48
+ elif α > φ:
49
+ i = [0, φ, α]
50
+ else:
51
+ i = i = [0, α]
52
+ return 1 - quad(lambda x: f(x)*sin(x), i)
53
+
54
+ y1 = lambda α: y(α, r)
55
+ y2 = lambda α: y(α, s)
56
+ y3 = lambda α: y2(α) - u(α)*sin(α)
57
+
58
+ S1 = quad(lambda x: y1(x)*r(x)*cos(x), [0, φ, θ, pi/2 - θ, pi/2 - φ])
59
+ S2 = quad(lambda x: y2(x)*s(x)*cos(x), [0, φ, θ])
60
+ S3 = quad(lambda x: y3(x)*(u(x)*sin(x) - du(x)*cos(x) - s(x)*cos(x)),
61
+ [φ, θ, pi/4])
62
+
63
+ print(2*(S1 + S2 + S3))
mpmath/source/demo/taylor.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Interval arithmetic demo: estimating error of numerical Taylor series.
3
+
4
+ This module can be run interactively with
5
+
6
+ python taylor.py
7
+
8
+ """
9
+ from mpmath import mpi, exp, factorial, mpf
10
+
11
+ def taylor(x, n):
12
+ print("-"*75)
13
+ t = x = mpi(x)
14
+ s = 1
15
+ print("adding 1")
16
+ print(s, "\n")
17
+ s += t
18
+ print("adding x")
19
+ print(s, "\n")
20
+ for k in range(2, n+1):
21
+ t = (t * x) / k
22
+ s += t
23
+ print("adding x^%i / %i! ~= %s" % (k, k, t.mid))
24
+ print(s, "\n")
25
+ print("-"*75)
26
+ return s
27
+
28
+ # Note: this should really be computed using interval arithmetic too!
29
+ def remainder(x, n):
30
+ xi = max(0, x)
31
+ r = exp(xi) / factorial(n+1)
32
+ r = r * x**(n+1)
33
+ return abs(r)
34
+
35
+ def exponential(x, n):
36
+ """
37
+ Compute exp(x) using n terms of the Taylor series for exp using
38
+ intervals, and print detailed error analysis.
39
+ """
40
+ t = taylor(x, n)
41
+ r = remainder(x, n)
42
+ expx = exp(x)
43
+ print("Correct value of exp(x): ", expx)
44
+ print()
45
+ print("Computed interval: ")
46
+ print(t)
47
+ print()
48
+ print("Computed value (midpoint): ", t.mid)
49
+ print()
50
+ print("Estimated rounding error: ", t.delta)
51
+ print("Estimated truncation error: ", r)
52
+ print("Estimated total error: ", t.delta + r)
53
+ print("Actual error ", abs(expx - t.mid))
54
+ print()
55
+ u = t + mpi(-r, r)
56
+ print("Interval with est. truncation error added:")
57
+ print(u)
58
+ print()
59
+ print("Correct value contained in computed interval:", t.a <= expx <= t.b)
60
+ print("When accounting for truncation error:", u.a <= expx <= u.b)
61
+
62
+ if __name__ == "__main__":
63
+ print("Interval arithmetic demo")
64
+ print()
65
+ print("This script sums the Taylor series for exp(x) using interval arithmetic,")
66
+ print("and then compares the numerical errors due to rounding and truncation.")
67
+ print()
68
+ x = mpf(input("Enter the value of x (e.g. 3.5): "))
69
+ n = int(input("Enter the number of terms n (e.g. 10): "))
70
+ print()
71
+ exponential(x, n)
mpmath/source/docs/basics.rst ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Basic usage
2
+ ===========================
3
+
4
+ To avoid inadvertently overriding other functions or objects, explicitly import
5
+ only the needed objects, or use the ``mpmath.`` or ``mp.`` namespaces::
6
+
7
+ >>> from mpmath import sin
8
+ >>> sin(1)
9
+ mpf('0.8414709848078965')
10
+
11
+ >>> import mpmath
12
+ >>> mpmath.sin(1)
13
+ mpf('0.8414709848078965')
14
+
15
+ >>> from mpmath import mp # mp context object -- to be explained
16
+ >>> mp.sin(1)
17
+ mpf('0.8414709848078965')
18
+
19
+ .. note::
20
+
21
+ Importing everything with ``from mpmath import *`` can be convenient,
22
+ especially when using mpmath interactively, but is best to avoid such
23
+ import statements in production code, as they make it unclear which
24
+ names are present in the namespace and wildcard-imported names may
25
+ conflict with other modules or variable names.
26
+
27
+ Number types
28
+ ------------
29
+
30
+ Mpmath provides the following numerical types:
31
+
32
+ +------------+----------------+
33
+ | Class | Description |
34
+ +============+================+
35
+ | ``mpf`` | Real float |
36
+ +------------+----------------+
37
+ | ``mpc`` | Complex float |
38
+ +------------+----------------+
39
+ | ``matrix`` | Matrix |
40
+ +------------+----------------+
41
+
42
+ The following section will provide a very short introduction to the types ``mpf`` and ``mpc``. Intervals and matrices are described further in the documentation chapters on interval arithmetic and matrices / linear algebra.
43
+
44
+ The ``mpf`` type is analogous to Python's built-in ``float``. It holds a real number or one of the special values ``inf`` (positive infinity), ``-inf`` (negative infinity) and ``nan`` (not-a-number, indicating an indeterminate result). You can create ``mpf`` instances from strings, integers, floats, and other ``mpf`` instances:
45
+
46
+ >>> from mpmath import mpf, mpc, mp
47
+ >>> mpf(4)
48
+ mpf('4.0')
49
+ >>> mpf(2.5)
50
+ mpf('2.5')
51
+ >>> mpf("1.25e6")
52
+ mpf('1250000.0')
53
+ >>> mpf(mpf(2))
54
+ mpf('2.0')
55
+ >>> mpf("inf")
56
+ mpf('inf')
57
+
58
+ The ``mpc`` type represents a complex number in rectangular form as a pair of ``mpf`` instances. It can be constructed from a Python ``complex``, a real number, or a pair of real numbers:
59
+
60
+ >>> mpc(2,3)
61
+ mpc(real='2.0', imag='3.0')
62
+ >>> mpc(complex(2,3)).imag
63
+ mpf('3.0')
64
+
65
+ You can mix ``mpf`` and ``mpc`` instances with each other and with Python numbers:
66
+
67
+ >>> mpf(3) + 2*mpf('2.5') + 1.0
68
+ mpf('9.0')
69
+ >>> mp.dps = 15 # Set precision (see below)
70
+ >>> mpc(1j)**0.5
71
+ mpc(real='0.70710678118654757', imag='0.70710678118654757')
72
+
73
+
74
+ Setting the precision
75
+ ---------------------
76
+
77
+ Mpmath uses a global working precision; it does not keep track of the precision or accuracy of individual numbers. Performing an arithmetic operation or calling ``mpf()`` rounds the result to the current working precision. The working precision is controlled by a context object called ``mp``, which has the following default state:
78
+
79
+ >>> print(mp)
80
+ Mpmath settings:
81
+ mp.prec = 53 [default: 53]
82
+ mp.dps = 15 [default: 15]
83
+ mp.rounding = 'n' [default: 'n']
84
+ mp.trap_complex = False [default: False]
85
+
86
+ The term **prec** denotes the binary precision (measured in bits) while **dps** (short for *decimal places*) is the decimal precision. Binary and decimal precision are related roughly according to the formula ``prec = 3.33*dps``. For example, it takes a precision of roughly 333 bits to hold an approximation of pi that is accurate to 100 decimal places (actually slightly more than 333 bits is used).
87
+
88
+ Changing either precision property of the ``mp`` object automatically updates the other; usually you just want to change the ``dps`` value:
89
+
90
+ >>> mp.dps = 100
91
+ >>> mp.dps
92
+ 100
93
+ >>> mp.prec
94
+ 336
95
+
96
+ When the precision has been set, all ``mpf`` operations are carried out at that precision::
97
+
98
+ >>> mp.dps = 50
99
+ >>> mpf(1) / 6
100
+ mpf('0.16666666666666666666666666666666666666666666666666656')
101
+ >>> mp.dps = 25
102
+ >>> mpf(2) ** mpf('0.5')
103
+ mpf('1.414213562373095048801688713')
104
+
105
+ The precision of complex arithmetic is also controlled by the ``mp`` object:
106
+
107
+ >>> mp.dps = 10
108
+ >>> mpc(1,2) / 3
109
+ mpc(real='0.3333333333321', imag='0.6666666666642')
110
+
111
+ There is no restriction on the magnitude of numbers. An ``mpf`` can for example hold an approximation of a large Mersenne prime:
112
+
113
+ >>> mp.dps = 15
114
+ >>> print(mpf(2)**32582657 - 1)
115
+ 1.24575026015369e+9808357
116
+
117
+ Or why not 1 googolplex:
118
+
119
+ >>> print(mpf(10) ** (10**100))
120
+ 1.0e+100000000000000000000000000000000000000000000000000...
121
+
122
+ The (binary) exponent is stored exactly and is independent of the precision.
123
+
124
+ The ``rounding`` property control default rounding mode for the context:
125
+
126
+ >>> mp.rounding # round to nearest
127
+ 'n'
128
+ >>> sin(1)
129
+ mpf('0.8414709848078965')
130
+ >>> mp.rounding = 'u' # round up
131
+ >>> sin(1)
132
+ mpf('0.84147098480789662')
133
+ >>> mp.rounding = 'n'
134
+
135
+ Temporarily changing the precision
136
+ ..................................
137
+
138
+ It is often useful to change the precision during only part of a calculation. A way to temporarily increase the precision and then restore it is as follows:
139
+
140
+ >>> mp.prec += 2
141
+ >>> # do_something()
142
+ >>> mp.prec -= 2
143
+
144
+ The ``with`` statement along with the mpmath functions ``workprec``, ``workdps``, ``extraprec`` and ``extradps`` can be used to temporarily change precision in a more safe manner:
145
+
146
+ >>> from mpmath import extradps, workdps
147
+ >>> with workdps(20):
148
+ ... print(mpf(1)/7)
149
+ ... with extradps(10):
150
+ ... print(mpf(1)/7)
151
+ ...
152
+ 0.14285714285714285714
153
+ 0.142857142857142857142857142857
154
+ >>> mp.dps
155
+ 15
156
+
157
+ The ``with`` statement ensures that the precision gets reset when exiting the block, even in the case that an exception is raised.
158
+
159
+ The ``workprec`` family of functions can also be used as function decorators:
160
+
161
+ >>> @workdps(6)
162
+ ... def f():
163
+ ... return mpf(1)/3
164
+ ...
165
+ >>> f()
166
+ mpf('0.33333331346511841')
167
+
168
+
169
+ Some functions accept the ``prec`` and ``dps`` keyword arguments and this will override the global working precision. Note that this will not affect the precision at which the result is printed, so to get all digits, you must either use increase precision afterward when printing or use ``nstr``/``nprint``:
170
+
171
+ >>> from mpmath import exp, nprint
172
+ >>> mp.dps = 15
173
+ >>> print(exp(1))
174
+ 2.71828182845905
175
+ >>> print(exp(1, dps=50)) # Extra digits won't be printed
176
+ 2.71828182845905
177
+ >>> nprint(exp(1, dps=50), 50)
178
+ 2.7182818284590452353602874713526624977572470937
179
+
180
+ Finally, instead of using the global context object ``mp``, you can create custom contexts and work with methods of those instances instead of global functions. The working precision will be local to each context object:
181
+
182
+ >>> mp2 = mp.clone()
183
+ >>> mp.dps = 10
184
+ >>> mp2.dps = 20
185
+ >>> print(mp.mpf(1) / 3)
186
+ 0.3333333333
187
+ >>> print(mp2.mpf(1) / 3)
188
+ 0.33333333333333333333
189
+
190
+ **Note**: the ability to create multiple contexts is a new feature that is only partially implemented. Not all mpmath functions are yet available as context-local methods. In the present version, you are likely to encounter bugs if you try mixing different contexts.
191
+
192
+ Providing correct input
193
+ -----------------------
194
+
195
+ Note that when creating a new ``mpf``, the value will at most be as accurate as the input. *Be careful when mixing mpmath numbers with Python floats*. When working at high precision, fractional ``mpf`` values should be created from strings or integers:
196
+
197
+ >>> mp.dps = 30
198
+ >>> mpf(10.9) # bad
199
+ mpf('10.9000000000000003552713678800501')
200
+ >>> mpf(1090/100) # bad, beware Python's true division produces floats
201
+ mpf('10.9000000000000003552713678800501')
202
+ >>> mpf('10.9') # good
203
+ mpf('10.8999999999999999999999999999997')
204
+ >>> mpf(109) / mpf(10) # also good
205
+ mpf('10.8999999999999999999999999999997')
206
+ >>> mp.dps = 15
207
+
208
+ (Binary fractions such as 0.5, 1.5, 0.75, 0.125, etc, are generally safe as input, however, since those can be represented exactly by Python floats.)
209
+
210
+ Printing
211
+ --------
212
+
213
+ By default, the ``repr()`` of a number includes its type signature. This way ``eval`` can be used to recreate a number from its string representation:
214
+
215
+ >>> eval(repr(mpf(2.5)))
216
+ mpf('2.5')
217
+
218
+ Prettier output can be obtained by using ``str()`` or ``print``, which hide the ``mpf`` and ``mpc`` signatures and also suppress rounding artifacts in the last few digits:
219
+
220
+ >>> mpf("3.14159")
221
+ mpf('3.1415899999999999')
222
+ >>> print(mpf("3.14159"))
223
+ 3.14159
224
+ >>> print(mpc(1j)**0.5)
225
+ (0.707106781186548 + 0.707106781186548j)
226
+
227
+ Setting the ``mp.pretty`` option will use the ``str()``-style output for ``repr()`` as well:
228
+
229
+ >>> mp.pretty = True
230
+ >>> mpf(0.6)
231
+ 0.6
232
+ >>> mp.pretty = False
233
+ >>> mpf(0.6)
234
+ mpf('0.59999999999999998')
235
+
236
+ To use enough digits to be able recreate value exactly, set ``mp.pretty_dps``
237
+ to ``"repr"`` (default value is ``"str"``). Same option is used to control
238
+ default number of digits in the new-style string formatting *without format
239
+ specifier*, i.e. ``format(exp(mpf(1)))``.
240
+
241
+ The number of digits with which numbers are printed by default is determined by
242
+ the working precision. To specify the number of digits to show without
243
+ changing the working precision, use :func:`format syntax support
244
+ <mpmath.mpf.__format__>` or functions :func:`mpmath.nstr` and
245
+ :func:`mpmath.nprint`:
246
+
247
+ >>> a = mpf(1) / 6
248
+ >>> a
249
+ mpf('0.16666666666666666')
250
+ >>> f'{a:.8}'
251
+ '0.16666667'
252
+ >>> f'{a:.50}'
253
+ '0.16666666666666665741480812812369549646973609924316'
mpmath/source/docs/calculus/approximation.rst ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Function approximation
2
+ ----------------------
3
+
4
+ Taylor series (``taylor``)
5
+ ..........................
6
+
7
+ .. autofunction:: mpmath.taylor
8
+
9
+ Pade approximation (``pade``)
10
+ .............................
11
+
12
+ .. autofunction:: mpmath.pade
13
+
14
+ Chebyshev approximation (``chebyfit``)
15
+ ......................................
16
+
17
+ .. autofunction:: mpmath.chebyfit
18
+
19
+ Fourier series (``fourier``, ``fourierval``)
20
+ ............................................
21
+
22
+ .. autofunction:: mpmath.fourier
23
+ .. autofunction:: mpmath.fourierval
mpmath/source/docs/calculus/differentiation.rst ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Differentiation
2
+ ---------------
3
+
4
+ Numerical derivatives (``diff``, ``diffs``)
5
+ ...........................................
6
+
7
+ .. autofunction:: mpmath.diff
8
+ .. autofunction:: mpmath.diffs
9
+
10
+ Composition of derivatives (``diffs_prod``, ``diffs_exp``)
11
+ ..........................................................
12
+
13
+ .. autofunction:: mpmath.diffs_prod
14
+ .. autofunction:: mpmath.diffs_exp
15
+
16
+ Fractional derivatives / differintegration (``differint``)
17
+ ............................................................
18
+
19
+ .. autofunction:: mpmath.differint
mpmath/source/docs/calculus/index.rst ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Numerical calculus
2
+ ==================
3
+
4
+ .. toctree::
5
+ :maxdepth: 2
6
+
7
+ polynomials
8
+ optimization
9
+ sums_limits
10
+ differentiation
11
+ integration
12
+ odes
13
+ approximation
14
+ inverselaplace
mpmath/source/docs/calculus/integration.rst ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Numerical integration (quadrature)
2
+ ----------------------------------
3
+
4
+ Standard quadrature (``quad``)
5
+ ..............................
6
+
7
+ .. autofunction:: mpmath.quad
8
+
9
+ Quadrature with subdivision (``quadsubdiv``)
10
+ ............................................
11
+
12
+ .. autofunction:: mpmath.quadsubdiv
13
+
14
+ Oscillatory quadrature (``quadosc``)
15
+ ....................................
16
+
17
+ .. autofunction:: mpmath.quadosc
18
+
19
+ Quadrature rules
20
+ ................
21
+
22
+ .. autoclass:: mpmath.calculus.quadrature.QuadratureRule
23
+ :members:
24
+
25
+ Tanh-sinh rule
26
+ ~~~~~~~~~~~~~~
27
+
28
+ .. autoclass:: mpmath.calculus.quadrature.TanhSinh
29
+ :members:
30
+
31
+
32
+ Gauss-Legendre rule
33
+ ~~~~~~~~~~~~~~~~~~~
34
+
35
+ .. autoclass:: mpmath.calculus.quadrature.GaussLegendre
36
+ :members:
mpmath/source/docs/calculus/inverselaplace.rst ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Numerical inverse Laplace transform
2
+ -----------------------------------
3
+
4
+ One-step algorithm (``invertlaplace``)
5
+ ......................................
6
+
7
+ .. autofunction:: mpmath.invertlaplace
8
+
9
+ Specific algorithms
10
+ ...................
11
+
12
+ Fixed Talbot algorithm
13
+ ~~~~~~~~~~~~~~~~~~~~~~
14
+
15
+ .. autoclass:: mpmath.calculus.inverselaplace.FixedTalbot
16
+ :members:
17
+
18
+ Gaver-Stehfest algorithm
19
+ ~~~~~~~~~~~~~~~~~~~~~~~~
20
+
21
+ .. autoclass:: mpmath.calculus.inverselaplace.Stehfest
22
+ :members:
23
+
24
+ de Hoog, Knight & Stokes algorithm
25
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
26
+
27
+ .. autoclass:: mpmath.calculus.inverselaplace.deHoog
28
+ :members:
29
+
30
+ Cohen acceleration algorithm
31
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
32
+
33
+ .. autoclass:: mpmath.calculus.inverselaplace.Cohen
34
+ :members:
35
+
36
+ Manual approach
37
+ ...............
38
+
39
+ It is possible and sometimes beneficial to re-create some of the
40
+ functionality in ``invertlaplace``. This could be used to compute the
41
+ Laplace-space function evaluations in a different way. For example,
42
+ the Laplace-space function evaluations could be the result of a
43
+ quadrature or sum, solution to a system of ordinary differential
44
+ equations, or possibly computed in parallel from some external library
45
+ or function call.
46
+
47
+ A trivial example showing the process (which could be implemented
48
+ using the existing interface):
49
+
50
+ >>> from mpmath import calculus, convert, exp, mp
51
+ >>> myTalbot = calculus.inverselaplace.FixedTalbot(mp)
52
+ >>> t = convert(0.25)
53
+ >>> myTalbot.calc_laplace_parameter(t)
54
+ >>> fp = lambda p: 1/(p + 1) - 1/(p + 1000)
55
+ >>> ft = lambda t: exp(-t) - exp(-1000*t)
56
+ >>> fpvec = [fp(p) for p in myTalbot.p]
57
+ >>> ft(t)-myTalbot.calc_time_domain_solution(fpvec,t,manual_prec=True)
58
+ mpf('1.928300179528890061756872185e-21')
59
+
60
+ This manual approach is also useful to look at the Laplace parameter,
61
+ order, or working precision which were computed.
62
+
63
+ >>> myTalbot.degree
64
+ 34
65
+
66
+ Credit
67
+ ......
68
+
69
+ The numerical inverse Laplace transform functionality was contributed
70
+ to mpmath by Kristopher L. Kuhlman in 2017. The Cohen method was contributed
71
+ to mpmath by Guillermo Navas-Palencia in 2022.
mpmath/source/docs/calculus/odes.rst ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ Ordinary differential equations
2
+ -------------------------------
3
+
4
+ Solving the ODE initial value problem (``odefun``)
5
+ ..................................................
6
+
7
+ .. autofunction:: mpmath.odefun
mpmath/source/docs/calculus/optimization.rst ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Root-finding and optimization
2
+ -----------------------------
3
+
4
+ Root-finding (``findroot``)
5
+ ...........................
6
+
7
+ .. autofunction:: mpmath.findroot(f, x0, solver=Secant, tol=None, verbose=False, verify=True, **kwargs)
8
+
9
+ Solvers
10
+ ^^^^^^^
11
+
12
+ .. autoclass:: mpmath.calculus.optimization.Secant
13
+ .. autoclass:: mpmath.calculus.optimization.Newton
14
+ .. autoclass:: mpmath.calculus.optimization.MNewton
15
+ .. autoclass:: mpmath.calculus.optimization.Halley
16
+ .. autoclass:: mpmath.calculus.optimization.Muller
17
+ .. autoclass:: mpmath.calculus.optimization.Bisection
18
+ .. autoclass:: mpmath.calculus.optimization.Illinois
19
+ .. autoclass:: mpmath.calculus.optimization.Pegasus
20
+ .. autoclass:: mpmath.calculus.optimization.Anderson
21
+ .. autoclass:: mpmath.calculus.optimization.Ridder
22
+ .. autoclass:: mpmath.calculus.optimization.ANewton
23
+ .. autoclass:: mpmath.calculus.optimization.MDNewton
mpmath/source/docs/calculus/polynomials.rst ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Polynomials
2
+ -----------
3
+
4
+ See also :func:`~mpmath.taylor` and :func:`~mpmath.chebyfit` for
5
+ approximation of functions by polynomials.
6
+
7
+ Polynomial evaluation (``polyval``)
8
+ ...................................
9
+
10
+ .. autofunction:: mpmath.polyval
11
+
12
+ Polynomial roots (``polyroots``)
13
+ ................................
14
+
15
+ .. autofunction:: mpmath.polyroots
mpmath/source/docs/calculus/sums_limits.rst ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Sums, products, limits and extrapolation
2
+ ----------------------------------------
3
+
4
+ The functions listed here permit approximation of infinite
5
+ sums, products, and other sequence limits.
6
+ Use :func:`mpmath.fsum` and :func:`mpmath.fprod`
7
+ for summation and multiplication of finite sequences.
8
+
9
+ Summation
10
+ ..........................................
11
+
12
+ :func:`~mpmath.nsum`
13
+ ^^^^^^^^^^^^^^^^^^^^^
14
+ .. autofunction:: mpmath.nsum
15
+
16
+ :func:`~mpmath.sumem`
17
+ ^^^^^^^^^^^^^^^^^^^^^
18
+ .. autofunction:: mpmath.sumem
19
+
20
+ :func:`~mpmath.sumap`
21
+ ^^^^^^^^^^^^^^^^^^^^^
22
+ .. autofunction:: mpmath.sumap
23
+
24
+ Products
25
+ ...............................
26
+
27
+ :func:`~mpmath.nprod`
28
+ ^^^^^^^^^^^^^^^^^^^^^^
29
+ .. autofunction:: mpmath.nprod
30
+
31
+ Limits (``limit``)
32
+ ..................
33
+
34
+ :func:`~mpmath.limit`
35
+ ^^^^^^^^^^^^^^^^^^^^^^
36
+ .. autofunction:: mpmath.limit
37
+
38
+ Extrapolation
39
+ ..........................................
40
+
41
+ The following functions provide a direct interface to
42
+ extrapolation algorithms. :func:`~mpmath.nsum` and :func:`~mpmath.limit`
43
+ essentially work by calling the following functions with an increasing
44
+ number of terms until the extrapolated limit is accurate enough.
45
+
46
+ The following functions may be useful to call directly if the
47
+ precise number of terms needed to achieve a desired accuracy is
48
+ known in advance, or if one wishes to study the convergence
49
+ properties of the algorithms.
50
+
51
+
52
+ :func:`~mpmath.richardson`
53
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
54
+ .. autofunction:: mpmath.richardson
55
+
56
+ :func:`~mpmath.shanks`
57
+ ^^^^^^^^^^^^^^^^^^^^^^^
58
+ .. autofunction:: mpmath.shanks
59
+
60
+ :func:`~mpmath.levin`
61
+ ^^^^^^^^^^^^^^^^^^^^^^
62
+ .. autofunction:: mpmath.levin
63
+
64
+ :func:`~mpmath.cohen_alt`
65
+ ^^^^^^^^^^^^^^^^^^^^^^^^^^
66
+ .. autofunction:: mpmath.cohen_alt
67
+
mpmath/source/docs/cli.rst ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ .. _cli:
2
+
3
+ Command-Line Usage
4
+ ==================
5
+
6
+ When called as a program from the command line, the following form is used:
7
+
8
+ .. autoprogram:: mpmath.__main__:parser
mpmath/source/docs/conf.py ADDED
@@ -0,0 +1,52 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Mpmath documentation build configuration file.
3
+
4
+ This file is execfile()d with the current directory set to its
5
+ containing dir.
6
+
7
+ The contents of this file are pickled, so don't put values in the
8
+ namespace that aren't pickleable (module imports are okay, they're
9
+ removed automatically).
10
+ """
11
+
12
+ import mpmath
13
+
14
+
15
+ # Add any Sphinx extension module names here, as strings.
16
+ extensions = ['sphinx.ext.autodoc', 'sphinx.ext.mathjax',
17
+ 'sphinx.ext.intersphinx', 'sphinxcontrib.autoprogram',
18
+ 'matplotlib.sphinxext.plot_directive']
19
+
20
+ # Sphinx will warn about all references where the target cannot be found.
21
+ nitpicky = True
22
+
23
+ # Project information.
24
+ project = mpmath.__name__
25
+ copyright = '2007-2026, Fredrik Johansson and mpmath developers'
26
+ release = version = mpmath.__version__
27
+
28
+ # Define how the current time is formatted using time.strftime().
29
+ today_fmt = '%B %d, %Y'
30
+
31
+ # The "theme" that the HTML output should use.
32
+ html_theme = 'classic'
33
+
34
+ # Grouping the document tree into LaTeX files. List of tuples
35
+ # (source start file, target name, title, author, document class [howto/manual]).
36
+ latex_documents = [('index', 'mpmath.tex', 'mpmath documentation',
37
+ r'Fredrik Johansson \and mpmath contributors', 'manual')]
38
+
39
+ # The name of default reST role, that is, for text marked up `like this`.
40
+ default_role = 'math'
41
+
42
+ # Contains mapping the locations and names of other projects that
43
+ # should be linked to in this documentation.
44
+ intersphinx_mapping = {
45
+ 'python': ('https://docs.python.org/3/', None),
46
+ 'sympy': ('https://docs.sympy.org/latest/', None),
47
+ }
48
+
49
+ plot_include_source = True
50
+ plot_formats = [('png', 96), 'pdf']
51
+ plot_html_show_formats = False
52
+ plot_html_show_source_link = False
mpmath/source/docs/contexts.rst ADDED
@@ -0,0 +1,370 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Contexts
2
+ ========
3
+
4
+ High-level code in mpmath is implemented as methods on a "context object". The context implements arithmetic, type conversions and other fundamental operations. The context also holds settings such as precision, and stores cache data. A few different contexts (with a mostly compatible interface) are provided so that the high-level algorithms can be used with different implementations of the underlying arithmetic, allowing different features and speed-accuracy tradeoffs. Currently, mpmath provides the following contexts:
5
+
6
+ * Arbitrary-precision arithmetic (``mp``)
7
+ * Arbitrary-precision interval arithmetic (``iv``)
8
+ * Double-precision arithmetic using Python's builtin ``float`` and ``complex`` types (``fp``)
9
+
10
+ .. note::
11
+
12
+ Using global context is not thread-safe, create instead
13
+ local contexts with e.g. :class:`~mpmath.MPContext`.
14
+
15
+ Most global functions in the global mpmath namespace are actually methods of the ``mp``
16
+ context. This fact is usually transparent to the user, but sometimes shows up in the
17
+ form of an initial parameter called "ctx" visible in the help for the function::
18
+
19
+ >>> import mpmath
20
+ >>> help(mpmath.fsum)
21
+ Help on method fsum in module mpmath.ctx_mp_python:
22
+ <BLANKLINE>
23
+ fsum(terms, absolute=False, squared=False) method of mpmath.ctx_mp.MPContext instance
24
+ Calculates a sum containing a finite number of terms (for infinite
25
+ series, see :func:`~mpmath.nsum`). The terms will be converted to
26
+ ...
27
+
28
+ The following operations are equivalent::
29
+
30
+ >>> mpmath.fsum([1,2,3])
31
+ mpf('6.0')
32
+ >>> mpmath.mp.fsum([1,2,3])
33
+ mpf('6.0')
34
+
35
+ The corresponding operation using the ``fp`` context::
36
+
37
+ >>> mpmath.fp.fsum([1,2,3])
38
+ 6.0
39
+
40
+ Common interface
41
+ ----------------
42
+
43
+ ``ctx.mpf`` creates a real number::
44
+
45
+ >>> from mpmath import mp, fp
46
+ >>> mp.mpf(3)
47
+ mpf('3.0')
48
+ >>> fp.mpf(3)
49
+ 3.0
50
+
51
+ ``ctx.mpc`` creates a complex number::
52
+
53
+ >>> mp.mpc(2,3)
54
+ mpc(real='2.0', imag='3.0')
55
+ >>> fp.mpc(2,3)
56
+ (2+3j)
57
+
58
+ ``ctx.matrix`` creates a matrix::
59
+
60
+ >>> mp.matrix([[1,0],[0,1]])
61
+ matrix(
62
+ [['1.0', '0.0'],
63
+ ['0.0', '1.0']])
64
+ >>> _[0,0]
65
+ mpf('1.0')
66
+ >>> fp.matrix([[1,0],[0,1]])
67
+ matrix(
68
+ [['1.0', '0.0'],
69
+ ['0.0', '1.0']])
70
+ >>> _[0,0]
71
+ 1.0
72
+
73
+ ``ctx.prec`` holds the current precision (in bits)::
74
+
75
+ >>> mp.prec
76
+ 53
77
+ >>> fp.prec
78
+ 53
79
+
80
+ ``ctx.dps`` holds the current precision (in digits)::
81
+
82
+ >>> mp.dps
83
+ 15
84
+ >>> fp.dps
85
+ 15
86
+
87
+ ``ctx.pretty`` controls whether objects should be pretty-printed automatically by :func:`repr`. Pretty-printing for ``mp`` numbers is disabled by default so that they can clearly be distinguished from Python numbers and so that ``eval(repr(x)) == x`` works::
88
+
89
+ >>> mp.mpf(3)
90
+ mpf('3.0')
91
+ >>> mpf = mp.mpf
92
+ >>> eval(repr(mp.mpf(3)))
93
+ mpf('3.0')
94
+ >>> mp.pretty = True
95
+ >>> mp.mpf(3)
96
+ 3.0
97
+ >>> fp.matrix([[1,0],[0,1]])
98
+ matrix(
99
+ [['1.0', '0.0'],
100
+ ['0.0', '1.0']])
101
+ >>> fp.pretty = True
102
+ >>> fp.matrix([[1,0],[0,1]])
103
+ [1.0 0.0]
104
+ [0.0 1.0]
105
+ >>> fp.pretty = False
106
+
107
+
108
+ Arbitrary-precision floating-point (``mp``)
109
+ ---------------------------------------------
110
+
111
+ The ``mp`` context is what most users probably want to use most of the time, as it supports the most functions, is most well-tested, and is implemented with a high level of optimization. Nearly all examples in this documentation use ``mp`` functions.
112
+
113
+ See :doc:`basics` for a description of basic usage.
114
+
115
+ .. autoclass:: mpmath.MPContext
116
+
117
+ Local contexts, created on demand, could be used just as the global ``mp``:
118
+
119
+ >>> from mpmath import MPContext
120
+ >>> ctx = MPContext()
121
+ >>> ctx.sin(1)
122
+ mpf('0.8414709848078965')
123
+ >>> ctx.prec = 113
124
+ >>> ctx.sin(1)
125
+ mpf('0.841470984807896506652502321630298954')
126
+
127
+ Arbitrary-precision interval arithmetic (``iv``)
128
+ ------------------------------------------------
129
+
130
+ The ``iv.mpf`` type represents a closed interval `[a,b]`; that is, the set `\{x : a \le x \le b\}`, where `a` and `b` are arbitrary-precision floating-point values, possibly `\pm \infty`. The ``iv.mpc`` type represents a rectangular complex interval `[a,b] + [c,d]i`; that is, the set `\{z = x+iy : a \le x \le b \land c \le y \le d\}`.
131
+
132
+ Interval arithmetic provides rigorous error tracking. If `f` is a mathematical function and `\hat f` is its interval arithmetic version, then the basic guarantee of interval arithmetic is that `f(v) \subseteq \hat f(v)` for any input interval `v`. Put differently, if an interval represents the known uncertainty for a fixed number, any sequence of interval operations will produce an interval that contains what would be the result of applying the same sequence of operations to the exact number. The principal drawbacks of interval arithmetic are speed (``iv`` arithmetic is typically at least two times slower than ``mp`` arithmetic) and that it sometimes provides far too pessimistic bounds.
133
+
134
+ .. note ::
135
+
136
+ The support for interval arithmetic in mpmath is still experimental, and many functions
137
+ do not yet properly support intervals. Please use this feature with caution.
138
+
139
+ Intervals can be created from single numbers (treated as zero-width intervals) or pairs of endpoint numbers. Strings are treated as exact decimal numbers. Note that a Python float like ``0.1`` generally does not represent the same number as its literal; use ``'0.1'`` instead::
140
+
141
+ >>> from mpmath import iv
142
+ >>> iv.mpf(3)
143
+ mpi('3.0', '3.0')
144
+ >>> print(iv.mpf(3))
145
+ [3.0, 3.0]
146
+ >>> iv.pretty = True
147
+ >>> iv.mpf([2,3])
148
+ [2.0, 3.0]
149
+ >>> iv.mpf(0.1) # probably not intended
150
+ [0.10000000000000000555, 0.10000000000000000555]
151
+ >>> iv.mpf('0.1') # good, gives a containing interval
152
+ [0.099999999999999991673, 0.10000000000000000555]
153
+ >>> iv.mpf(['0.1', '0.2'])
154
+ [0.099999999999999991673, 0.2000000000000000111]
155
+
156
+ The fact that ``'0.1'`` results in an interval of nonzero width indicates that 1/10 cannot be represented using binary floating-point numbers at this precision level (in fact, it cannot be represented exactly at any precision).
157
+
158
+ Intervals may be infinite or half-infinite::
159
+
160
+ >>> print(1 / iv.mpf([2, 'inf']))
161
+ [0.0, 0.5]
162
+
163
+ The equality testing operators ``==`` and ``!=`` check whether their operands
164
+ are identical as intervals; that is, have the same endpoints. The ordering
165
+ operators ``< <= > >=`` permit inequality testing using triple-valued logic: a
166
+ guaranteed inequality returns ``True`` or ``False`` while an indeterminate
167
+ inequality raises :exc:`ValueError`::
168
+
169
+ >>> iv.mpf([1,2]) == iv.mpf([1,2])
170
+ True
171
+ >>> iv.mpf([1,2]) != iv.mpf([1,2])
172
+ False
173
+ >>> iv.mpf([1,2]) <= 2
174
+ True
175
+ >>> iv.mpf([1,2]) > 0
176
+ True
177
+ >>> iv.mpf([1,2]) < 1
178
+ False
179
+ >>> iv.mpf([1,2]) < 2
180
+ Traceback (most recent call last):
181
+ ...
182
+ ValueError
183
+ >>> iv.mpf([2,2]) < 2
184
+ False
185
+ >>> iv.mpf([1,2]) <= iv.mpf([2,3])
186
+ True
187
+ >>> iv.mpf([1,2]) < iv.mpf([2,3])
188
+ Traceback (most recent call last):
189
+ ...
190
+ ValueError
191
+ >>> iv.mpf([1,2]) < iv.mpf([-1,0])
192
+ False
193
+
194
+ The ``in`` operator tests whether a number or interval is contained in another interval::
195
+
196
+ >>> iv.mpf([0,2]) in iv.mpf([0,10])
197
+ True
198
+ >>> 3 in iv.mpf(['-inf', 0])
199
+ False
200
+
201
+ Intervals have the properties ``.a``, ``.b`` (endpoints), ``.mid``, and ``.delta`` (width)::
202
+
203
+ >>> x = iv.mpf([2, 5])
204
+ >>> x.a
205
+ [2.0, 2.0]
206
+ >>> x.b
207
+ [5.0, 5.0]
208
+ >>> x.mid
209
+ [3.5, 3.5]
210
+ >>> x.delta
211
+ [3.0, 3.0]
212
+
213
+ Some transcendental functions are supported::
214
+
215
+ >>> iv.dps = 15
216
+ >>> mp.dps = 15
217
+ >>> iv.mpf([0.5,1.5]) ** iv.mpf([0.5, 1.5])
218
+ [0.35355339059327373086, 1.837117307087383633]
219
+ >>> iv.exp(0)
220
+ [1.0, 1.0]
221
+ >>> iv.exp(['-inf','inf'])
222
+ [0.0, inf]
223
+ >>>
224
+ >>> iv.exp(['-inf',0])
225
+ [0.0, 1.0]
226
+ >>> iv.exp([0,'inf'])
227
+ [1.0, inf]
228
+ >>> iv.exp([0,1])
229
+ [1.0, 2.7182818284590455349]
230
+ >>>
231
+ >>> iv.log(1)
232
+ [0.0, 0.0]
233
+ >>> iv.log([0,1])
234
+ [-inf, 0.0]
235
+ >>> iv.log([0,'inf'])
236
+ [-inf, inf]
237
+ >>> iv.log(2)
238
+ [0.69314718055994528623, 0.69314718055994539725]
239
+ >>>
240
+ >>> iv.sin([100,'inf'])
241
+ [-1.0, 1.0]
242
+ >>> iv.cos(['-0.1','0.1'])
243
+ [0.99500416527802570954, 1.0]
244
+
245
+ Interval arithmetic is useful for proving inequalities involving irrational numbers.
246
+ Naive use of ``mp`` arithmetic may result in wrong conclusions, such as the following::
247
+
248
+ >>> mp.dps = 25
249
+ >>> x = mp.exp(mp.pi*mp.sqrt(163))
250
+ >>> y = mp.mpf(640320**3+744)
251
+ >>> print(x)
252
+ 262537412640768744.0000001
253
+ >>> print(y)
254
+ 262537412640768744.0
255
+ >>> x > y
256
+ True
257
+
258
+ But the correct result is `e^{\pi \sqrt{163}} < 262537412640768744`, as can be
259
+ seen by increasing the precision::
260
+
261
+ >>> mp.dps = 50
262
+ >>> print(mp.exp(mp.pi*mp.sqrt(163)))
263
+ 262537412640768743.99999999999925007259719818568888
264
+
265
+ With interval arithmetic, the comparison raises :exc:`ValueError` until the
266
+ precision is large enough for `x-y` to have a definite sign::
267
+
268
+ >>> iv.dps = 15
269
+ >>> iv.exp(iv.pi*iv.sqrt(163)) > (640320**3+744)
270
+ Traceback (most recent call last):
271
+ ...
272
+ ValueError
273
+ >>> iv.dps = 30
274
+ >>> iv.exp(iv.pi*iv.sqrt(163)) > (640320**3+744)
275
+ Traceback (most recent call last):
276
+ ...
277
+ ValueError
278
+ >>> iv.dps = 60
279
+ >>> iv.exp(iv.pi*iv.sqrt(163)) > (640320**3+744)
280
+ False
281
+ >>> iv.dps = 15
282
+
283
+ Fast low-precision arithmetic (``fp``)
284
+ ---------------------------------------------
285
+
286
+ Although mpmath is generally designed for arbitrary-precision arithmetic, many of the high-level algorithms work perfectly well with ordinary Python ``float`` and ``complex`` numbers, which use hardware double precision (on most systems, this corresponds to 53 bits of precision). Whereas the global functions (which are methods of the ``mp`` object) always convert inputs to mpmath numbers, the ``fp`` object instead converts them to ``float`` or ``complex``, and in some cases employs basic functions optimized for double precision. When large amounts of function evaluations (numerical integration, plotting, etc) are required, and when ``fp`` arithmetic provides sufficient accuracy, this can give a significant speedup over ``mp`` arithmetic.
287
+
288
+ To take advantage of this feature, simply use the ``fp`` prefix, i.e. write ``fp.func`` instead of ``func`` or ``mp.func``::
289
+
290
+ >>> u = fp.erfc(0.5)
291
+ >>> print(u)
292
+ 0.4795001221869535
293
+ >>> type(u)
294
+ <class 'float'>
295
+ >>> mp.dps = 16
296
+ >>> print(mp.erfc(0.5))
297
+ 0.4795001221869535
298
+ >>> fp.matrix([[1,2],[3,4]]) ** 2
299
+ matrix(
300
+ [['7.0', '10.0'],
301
+ ['15.0', '22.0']])
302
+ >>>
303
+ >>> type(_[0,0])
304
+ <class 'float'>
305
+ >>> print(fp.quad(fp.sin, [0, fp.pi])) # numerical integration
306
+ 2.0
307
+
308
+ The ``fp`` context wraps Python's ``math`` and ``cmath`` modules for elementary functions. It supports both real and complex numbers and automatically generates complex results for real inputs (``math`` raises an exception)::
309
+
310
+ >>> fp.sqrt(5)
311
+ 2.23606797749979
312
+ >>> fp.sqrt(-5)
313
+ 2.23606797749979j
314
+ >>> fp.sin(10)
315
+ -0.5440211108893698
316
+ >>> fp.power(-1, 0.25)
317
+ (0.7071067811865476+0.7071067811865475j)
318
+ >>> (-1) ** 0.25
319
+ (0.7071067811865476+0.7071067811865475j)
320
+
321
+ The ``prec`` and ``dps`` attributes can be changed (for interface compatibility with the ``mp`` context) but this has no effect::
322
+
323
+ >>> fp.prec
324
+ 53
325
+ >>> fp.dps
326
+ 15
327
+ >>> fp.prec = 80
328
+ >>> fp.prec
329
+ 53
330
+ >>> fp.dps
331
+ 15
332
+
333
+ Due to intermediate rounding and cancellation errors, results computed with ``fp`` arithmetic may be much less accurate than those computed with ``mp`` using an equivalent precision (``mp.prec = 53``), since the latter often uses increased internal precision. The accuracy is highly problem-dependent: for some functions, ``fp`` almost always gives 14-15 correct digits; for others, results can be accurate to only 2-3 digits or even completely wrong. The recommended use for ``fp`` is therefore to speed up large-scale computations where accuracy can be verified in advance on a subset of the input set, or where results can be verified afterwards.
334
+
335
+ Beware that the ``fp`` context has signed zero, that can be used to distinguish
336
+ different sides of branch cuts. For example, ``fp.mpc(-1, -0.0)`` is treated
337
+ as though it lies *below* the branch cut for :func:`~mpmath.sqrt()`::
338
+
339
+ >>> fp.sqrt(fp.mpc(-1, -0.0))
340
+ -1j
341
+ >>> fp.sqrt(fp.mpc(-1, -1e-10))
342
+ (5e-11-1j)
343
+
344
+ But an argument of ``fp.mpc(-1, 0.0)`` is treated as though it lies *above* the
345
+ branch cut::
346
+
347
+ >>> fp.sqrt(fp.mpc(-1, +0.0))
348
+ 1j
349
+ >>> fp.sqrt(fp.mpc(-1, +1e-10))
350
+ (5e-11+1j)
351
+
352
+
353
+ While near the branch cut, for small but nonzero deviations in components
354
+ results agreed with the ``mp`` contexts::
355
+
356
+ >>> fp.mpc(mp.sqrt(mp.mpc(-1, -1e-10)))
357
+ (5e-11-1j)
358
+ >>> fp.mpc(mp.sqrt(mp.mpc(-1, +1e-10)))
359
+ (5e-11+1j)
360
+
361
+ one has no signed zeros and allows to specify result *on the branch cut*
362
+ (nonpositive part of the real axis in this example)::
363
+
364
+ >>> fp.mpc(mp.sqrt(mp.mpc(-1, 0)))
365
+ 1j
366
+ >>> fp.mpc(mp.sqrt(-1))
367
+ 1j
368
+
369
+ Here it's continuous from the above of the :func:`~mpmath.sqrt()` branch
370
+ cut (from ``0`` along the negative real axis to the negative infinity).
mpmath/source/docs/functions/bessel.rst ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Bessel functions and related functions
2
+ --------------------------------------
3
+
4
+ The functions in this section arise as solutions to various differential
5
+ equations in physics, typically describing wavelike oscillatory behavior or a
6
+ combination of oscillation and exponential decay or growth. Mathematically,
7
+ they are special cases of the confluent hypergeometric functions `\,_0F_1`,
8
+ `\,_1F_1` and `\,_1F_2` (see :doc:`hypergeometric`).
9
+
10
+
11
+ Bessel functions
12
+ ................
13
+
14
+ .. autofunction:: mpmath.besselj
15
+ .. autofunction:: mpmath.j0
16
+ .. autofunction:: mpmath.j1
17
+ .. autofunction:: mpmath.bessely
18
+ .. autofunction:: mpmath.besseli
19
+ .. autofunction:: mpmath.besselk
20
+
21
+
22
+ Bessel function zeros
23
+ .....................
24
+
25
+ .. autofunction:: mpmath.besseljzero
26
+ .. autofunction:: mpmath.besselyzero
27
+
28
+
29
+ Hankel functions
30
+ ................
31
+
32
+ .. autofunction:: mpmath.hankel1
33
+ .. autofunction:: mpmath.hankel2
34
+
35
+
36
+ Spherical Bessel functions
37
+ ..........................
38
+
39
+ .. autofunction:: mpmath.spherical_jn
40
+ .. autofunction:: mpmath.spherical_yn
41
+
42
+
43
+ Kelvin functions
44
+ ................
45
+
46
+ .. autofunction:: mpmath.ber
47
+ .. autofunction:: mpmath.bei
48
+ .. autofunction:: mpmath.ker
49
+ .. autofunction:: mpmath.kei
50
+
51
+
52
+ Struve functions
53
+ ................
54
+
55
+ .. autofunction:: mpmath.struveh
56
+ .. autofunction:: mpmath.struvel
57
+
58
+
59
+ Anger-Weber functions
60
+ .....................
61
+
62
+ .. autofunction:: mpmath.angerj
63
+ .. autofunction:: mpmath.webere
64
+
65
+
66
+ Lommel functions
67
+ ................
68
+
69
+ .. autofunction:: mpmath.lommels1
70
+ .. autofunction:: mpmath.lommels2
71
+
72
+
73
+ Airy and Scorer functions
74
+ .........................
75
+
76
+ .. autofunction:: mpmath.airyai
77
+ .. autofunction:: mpmath.airybi
78
+ .. autofunction:: mpmath.airyaizero
79
+ .. autofunction:: mpmath.airybizero
80
+ .. autofunction:: mpmath.scorergi
81
+ .. autofunction:: mpmath.scorerhi
82
+
83
+
84
+ Coulomb wave functions
85
+ ......................
86
+
87
+ .. autofunction:: mpmath.coulombf
88
+ .. autofunction:: mpmath.coulombg
89
+ .. autofunction:: mpmath.coulombc
90
+
91
+
92
+ Confluent U and Whittaker functions
93
+ ...................................
94
+
95
+ .. autofunction:: mpmath.hyperu(a, b, z)
96
+ .. autofunction:: mpmath.whitm(k,m,z)
97
+ .. autofunction:: mpmath.whitw(k,m,z)
98
+
99
+
100
+ Parabolic cylinder functions
101
+ ............................
102
+
103
+ .. autofunction:: mpmath.pcfd
104
+ .. autofunction:: mpmath.pcfu
105
+ .. autofunction:: mpmath.pcfv
106
+ .. autofunction:: mpmath.pcfw
mpmath/source/docs/functions/constants.rst ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Mathematical constants
2
+ ----------------------
3
+
4
+ Mpmath supports arbitrary-precision computation of various common (and less
5
+ common) mathematical constants. These constants are implemented as lazy
6
+ objects that can evaluate to any precision. Whenever the objects are used as
7
+ function arguments or as operands in arithmetic operations, they automagically
8
+ evaluate to the current working precision. A lazy number can be converted to a
9
+ regular ``mpf`` using the unary ``+`` operator, or by calling it as a
10
+ function::
11
+
12
+ >>> from mpmath import pi, mp
13
+ >>> pi
14
+ <pi: 3.14159~>
15
+ >>> 2*pi
16
+ mpf('6.2831853071795862')
17
+ >>> +pi
18
+ mpf('3.1415926535897931')
19
+ >>> pi()
20
+ mpf('3.1415926535897931')
21
+ >>> mp.dps = 40
22
+ >>> pi
23
+ <pi: 3.14159~>
24
+ >>> 2*pi
25
+ mpf('6.283185307179586476925286766559005768394338')
26
+ >>> +pi
27
+ mpf('3.141592653589793238462643383279502884197169')
28
+ >>> pi()
29
+ mpf('3.141592653589793238462643383279502884197169')
30
+
31
+ The predefined objects ``j`` (imaginary unit), ``inf`` (positive infinity) and
32
+ ``nan`` (not-a-number) are shortcuts to ``mpc`` and ``mpf`` instances with
33
+ these fixed values.
34
+
35
+ .. autofunction:: mpmath.mp.pi
36
+ .. autoattribute:: mpmath.mp.degree
37
+ .. autoattribute:: mpmath.mp.e
38
+ .. autoattribute:: mpmath.mp.phi
39
+ .. autofunction:: mpmath.mp.euler
40
+ .. autoattribute:: mpmath.mp.catalan
41
+ .. autoattribute:: mpmath.mp.apery
42
+ .. autoattribute:: mpmath.mp.khinchin
43
+ .. autoattribute:: mpmath.mp.glaisher
44
+ .. autoattribute:: mpmath.mp.mertens
45
+ .. autoattribute:: mpmath.mp.twinprime
mpmath/source/docs/functions/elliptic.rst ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Elliptic functions
2
+ ------------------
3
+
4
+ .. automodule:: mpmath.functions.elliptic
5
+ :no-index:
6
+
7
+
8
+ Elliptic arguments
9
+ ..................
10
+
11
+ .. autofunction:: mpmath.qfrom
12
+ .. autofunction:: mpmath.qbarfrom
13
+ .. autofunction:: mpmath.mfrom
14
+ .. autofunction:: mpmath.kfrom
15
+ .. autofunction:: mpmath.taufrom
16
+
17
+
18
+ Legendre elliptic integrals
19
+ ...........................
20
+
21
+ .. autofunction:: mpmath.ellipk
22
+ .. autofunction:: mpmath.ellipf
23
+ .. autofunction:: mpmath.ellipe
24
+ .. autofunction:: mpmath.ellippi
25
+
26
+
27
+ Carlson symmetric elliptic integrals
28
+ ....................................
29
+
30
+ .. autofunction:: mpmath.elliprf
31
+ .. autofunction:: mpmath.elliprc
32
+ .. autofunction:: mpmath.elliprj
33
+ .. autofunction:: mpmath.elliprd
34
+ .. autofunction:: mpmath.elliprg
35
+
36
+
37
+ Jacobi theta functions
38
+ ......................
39
+
40
+ .. autofunction:: mpmath.jtheta
41
+
42
+
43
+ Jacobi elliptic functions
44
+ .........................
45
+
46
+ .. autofunction:: mpmath.ellipfun
47
+
48
+
49
+ Modular functions
50
+ .................
51
+
52
+ .. autofunction:: mpmath.eta
53
+ .. autofunction:: mpmath.kleinj
mpmath/source/docs/functions/expintegrals.rst ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Exponential integrals and error functions
2
+ -----------------------------------------
3
+
4
+ Exponential integrals give closed-form solutions to a large class of commonly
5
+ occurring transcendental integrals that cannot be evaluated using elementary
6
+ functions. Integrals of this type include those with an integrand of the form
7
+ `t^a e^{t}` or `e^{-x^2}`, the latter giving rise to the Gaussian (or normal)
8
+ probability distribution.
9
+
10
+ The most general function in this section is the incomplete gamma function, to
11
+ which all others can be reduced. The incomplete gamma function, in turn, can
12
+ be expressed using hypergeometric functions (see :doc:`hypergeometric`).
13
+
14
+ Incomplete gamma functions
15
+ ..........................
16
+
17
+ .. autofunction:: mpmath.gammainc
18
+ .. autofunction:: mpmath.lower_gamma
19
+ .. autofunction:: mpmath.upper_gamma
20
+
21
+
22
+ Exponential integrals
23
+ .....................
24
+
25
+ .. autofunction:: mpmath.ei
26
+ .. autofunction:: mpmath.e1
27
+ .. autofunction:: mpmath.expint
28
+
29
+
30
+ Logarithmic integral
31
+ ....................
32
+
33
+ .. autofunction:: mpmath.li
34
+
35
+
36
+ Trigonometric integrals
37
+ .......................
38
+
39
+ .. autofunction:: mpmath.ci
40
+ .. autofunction:: mpmath.si
41
+
42
+
43
+ Hyperbolic integrals
44
+ ....................
45
+
46
+ .. autofunction:: mpmath.chi
47
+ .. autofunction:: mpmath.shi
48
+
49
+
50
+ Error functions
51
+ ...............
52
+
53
+ .. autofunction:: mpmath.erf
54
+ .. autofunction:: mpmath.erfc
55
+ .. autofunction:: mpmath.erfi
56
+ .. autofunction:: mpmath.erfinv
57
+
58
+
59
+ The normal distribution
60
+ .......................
61
+
62
+ .. autofunction:: mpmath.npdf
63
+ .. autofunction:: mpmath.ncdf
64
+
65
+
66
+ Fresnel integrals
67
+ .................
68
+
69
+ .. autofunction:: mpmath.fresnels
70
+ .. autofunction:: mpmath.fresnelc
mpmath/source/docs/functions/gamma.rst ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Factorials and gamma functions
2
+ ------------------------------
3
+
4
+ Factorials and factorial-like sums and products are basic tools of
5
+ combinatorics and number theory. Much like the exponential function is
6
+ fundamental to differential equations and analysis in general, the factorial
7
+ function (and its extension to complex numbers, the gamma function) is
8
+ fundamental to difference equations and functional equations.
9
+
10
+ A large selection of factorial-like functions is implemented in mpmath. All
11
+ functions support complex arguments, and arguments may be arbitrarily large.
12
+ Results are numerical approximations, so to compute *exact* values a high
13
+ enough precision must be set manually::
14
+
15
+ >>> from mpmath import mp, fac
16
+ >>> mp.dps = 15
17
+ >>> mp.pretty = True
18
+ >>> fac(100)
19
+ 9.33262154439442e+157
20
+ >>> print(int(_)) # most digits are wrong
21
+ 93326215443944150965646704795953882578400970373184098831012889540582227238570431295066113089288327277825849664006524270554535976289719382852181865895959724032
22
+ >>> mp.dps = 160
23
+ >>> fac(100)
24
+ 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000.0
25
+
26
+ The gamma and polygamma functions are closely related to :doc:`zeta`. See also
27
+ :doc:`qfunctions` for q-analogs of factorial-like functions.
28
+
29
+
30
+ Factorials
31
+ ..........
32
+
33
+ .. autofunction:: mpmath.factorial
34
+ .. autofunction:: mpmath.fac2
35
+
36
+
37
+ Binomial coefficients
38
+ .....................
39
+
40
+ .. autofunction:: mpmath.binomial
41
+
42
+
43
+ Gamma function
44
+ ..............
45
+
46
+ .. autofunction:: mpmath.gamma
47
+ .. autofunction:: mpmath.rgamma
48
+ .. autofunction:: mpmath.gammaprod
49
+ .. autofunction:: mpmath.loggamma
50
+
51
+
52
+ Rising and falling factorials
53
+ .............................
54
+
55
+ .. autofunction:: mpmath.rf
56
+ .. autofunction:: mpmath.ff
57
+
58
+
59
+ Beta function
60
+ .............
61
+
62
+ .. autofunction:: mpmath.beta
63
+ .. autofunction:: mpmath.betainc
64
+
65
+
66
+ Super- and hyperfactorials
67
+ ..........................
68
+
69
+ .. autofunction:: mpmath.superfac
70
+ .. autofunction:: mpmath.hyperfac
71
+ .. autofunction:: mpmath.barnesg
72
+
73
+
74
+ Polygamma functions and harmonic numbers
75
+ ........................................
76
+
77
+ .. autofunction:: mpmath.psi
78
+ .. autofunction:: mpmath.digamma
79
+ .. autofunction:: mpmath.harmonic
mpmath/source/docs/functions/hyperbolic.rst ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Hyperbolic functions
2
+ --------------------
3
+
4
+ Hyperbolic functions
5
+ ....................
6
+
7
+ .. autofunction:: mpmath.cosh
8
+ .. autofunction:: mpmath.sinh
9
+ .. autofunction:: mpmath.tanh
10
+ .. autofunction:: mpmath.sech
11
+ .. autofunction:: mpmath.csch
12
+ .. autofunction:: mpmath.coth
13
+
14
+
15
+ Inverse hyperbolic functions
16
+ ............................
17
+
18
+ .. autofunction:: mpmath.acosh
19
+ .. autofunction:: mpmath.asinh
20
+ .. autofunction:: mpmath.atanh
21
+ .. autofunction:: mpmath.asech
22
+ .. autofunction:: mpmath.acsch
23
+ .. autofunction:: mpmath.acoth
mpmath/source/docs/functions/hypergeometric.rst ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Hypergeometric functions
2
+ ------------------------
3
+
4
+ The functions listed in :doc:`expintegrals`, :doc:`bessel` and
5
+ :doc:`orthogonal`, and many other functions as well, are merely particular
6
+ instances of the generalized hypergeometric function `\,_pF_q`. The functions
7
+ listed in the following section enable efficient direct evaluation of the
8
+ underlying hypergeometric series, as well as linear combinations, limits with
9
+ respect to parameters, and analytic continuations thereof. Extensions to
10
+ twodimensional series are also provided. See also the basic or q-analog of the
11
+ hypergeometric series in :doc:`qfunctions`.
12
+
13
+ For convenience, most of the hypergeometric series of low order are provided as
14
+ standalone functions. They can equivalently be evaluated using
15
+ :func:`~mpmath.hyper`. As will be demonstrated in the respective docstrings,
16
+ all the ``hyp#f#`` functions implement analytic continuations and/or asymptotic
17
+ expansions with respect to the argument `z`, thereby permitting evaluation for
18
+ `z` anywhere in the complex plane. Functions of higher degree can be computed
19
+ via :func:`~mpmath.hyper`, but generally only in rapidly convergent instances.
20
+
21
+ Most hypergeometric and hypergeometric-derived functions accept optional
22
+ keyword arguments to specify options for :func:`~mpmath.hypercomb` or
23
+ :func:`~mpmath.hyper`. Some useful options are *maxprec*, *maxterms*,
24
+ *zeroprec*, *accurate_small*, *hmag*, *force_series*, *asymp_tol* and
25
+ *eliminate*. These options give control over what to do in case of slow
26
+ convergence, extreme loss of accuracy or evaluation at zeros (these two cases
27
+ cannot generally be distinguished from each other automatically), and singular
28
+ parameter combinations.
29
+
30
+ Common hypergeometric series
31
+ ............................
32
+
33
+ .. autofunction:: mpmath.hyp0f1
34
+ .. autofunction:: mpmath.hyp1f1
35
+ .. autofunction:: mpmath.hyp1f2
36
+ .. autofunction:: mpmath.hyp2f0
37
+ .. autofunction:: mpmath.hyp2f1
38
+ .. autofunction:: mpmath.hyp2f2
39
+ .. autofunction:: mpmath.hyp2f3
40
+ .. autofunction:: mpmath.hyp3f2
41
+
42
+
43
+ Generalized hypergeometric functions
44
+ ....................................
45
+
46
+ .. autofunction:: mpmath.hyper
47
+ .. autofunction:: mpmath.hypercomb
48
+
49
+
50
+ Meijer G-function
51
+ .................
52
+
53
+ .. autofunction:: mpmath.meijerg
54
+
55
+ Fox H-function
56
+ .................
57
+
58
+ .. autofunction:: mpmath.foxh
59
+
60
+
61
+ Bilateral hypergeometric series
62
+ ...............................
63
+
64
+ .. autofunction:: mpmath.bihyper
65
+
66
+
67
+ Hypergeometric functions of two variables
68
+ .........................................
69
+
70
+ .. autofunction:: mpmath.hyper2d
71
+ .. autofunction:: mpmath.appellf1
72
+ .. autofunction:: mpmath.appellf2
73
+ .. autofunction:: mpmath.appellf3
74
+ .. autofunction:: mpmath.appellf4
mpmath/source/docs/functions/index.rst ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Mathematical functions
2
+ ======================
3
+
4
+ Mpmath implements the standard functions from Python's ``math`` and ``cmath`` modules, for both real and complex numbers and with arbitrary precision. Many other functions are also available in mpmath, including commonly-used variants of standard functions (such as the alternative trigonometric functions sec, csc, cot), but also a large number of "special functions" such as the gamma function, the Riemann zeta function, error functions, Bessel functions, etc.
5
+
6
+ .. toctree::
7
+ :maxdepth: 2
8
+
9
+ constants
10
+ powers
11
+ trigonometric
12
+ hyperbolic
13
+ signals
14
+ gamma
15
+ expintegrals
16
+ bessel
17
+ orthogonal
18
+ hypergeometric
19
+ elliptic
20
+ zeta
21
+ numtheory
22
+ qfunctions
mpmath/source/docs/functions/numtheory.rst ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Number-theoretical, combinatorial and integer functions
2
+ -------------------------------------------------------
3
+
4
+ For factorial-type functions, including binomial coefficients, double
5
+ factorials, etc, see the separate section :doc:`gamma`.
6
+
7
+ Fibonacci numbers
8
+ .................
9
+
10
+ .. autofunction:: mpmath.fibonacci
11
+
12
+
13
+ Bernoulli numbers and polynomials
14
+ .................................
15
+
16
+ .. autofunction:: mpmath.bernoulli
17
+ .. autofunction:: mpmath.bernfrac
18
+ .. autofunction:: mpmath.bernpoly
19
+
20
+
21
+ Euler numbers and polynomials
22
+ .............................
23
+
24
+ .. autofunction:: mpmath.eulernum
25
+ .. autofunction:: mpmath.eulerpoly
26
+
27
+
28
+ Bell numbers and polynomials
29
+ ............................
30
+
31
+ .. autofunction:: mpmath.bell
32
+
33
+
34
+ Stirling numbers
35
+ ................
36
+
37
+ .. autofunction:: mpmath.stirling1
38
+ .. autofunction:: mpmath.stirling2
39
+
40
+
41
+ Prime counting functions
42
+ ........................
43
+
44
+ .. autofunction:: mpmath.primepi
45
+ .. autofunction:: mpmath.primepi2
46
+ .. autofunction:: mpmath.riemannr
47
+
48
+
49
+ Cyclotomic polynomials
50
+ ......................
51
+
52
+ .. autofunction:: mpmath.cyclotomic
53
+
54
+
55
+ Arithmetic functions
56
+ ......................
57
+
58
+ .. autofunction:: mpmath.mangoldt