Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- env-llmeval/lib/python3.10/site-packages/mpmath/__init__.py +468 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp_python.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/function_docs.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/ctx_fp.py +253 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/ctx_iv.py +551 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/ctx_mp.py +1339 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/function_docs.py +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/math2.py +672 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__init__.py +2 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/matrices/eigen_symmetric.py +1807 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/rational.py +240 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__init__.py +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/extratest_zeta.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_basic_ops.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_bitwise.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_calculus.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_diff.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_division.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_eigen.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_eigen_symmetric.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_fp.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_functions.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_functions2.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_hp.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_identify.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_interval.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_levin.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_matrices.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_mpmath.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_ode.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_pickle.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_power.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_quad.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_rootfinding.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_special.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_trig.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_visualization.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/torture.cpython-310.pyc +0 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/extratest_gamma.py +215 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/extratest_zeta.py +30 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/runtests.py +161 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_basic_ops.py +451 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_bitwise.py +188 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_calculus.py +216 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_compatibility.py +77 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_convert.py +233 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_diff.py +61 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_division.py +143 -0
- env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_eigen.py +179 -0
env-llmeval/lib/python3.10/site-packages/mpmath/__init__.py
ADDED
@@ -0,0 +1,468 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
__version__ = '1.3.0'
|
2 |
+
|
3 |
+
from .usertools import monitor, timing
|
4 |
+
|
5 |
+
from .ctx_fp import FPContext
|
6 |
+
from .ctx_mp import MPContext
|
7 |
+
from .ctx_iv import MPIntervalContext
|
8 |
+
|
9 |
+
fp = FPContext()
|
10 |
+
mp = MPContext()
|
11 |
+
iv = MPIntervalContext()
|
12 |
+
|
13 |
+
fp._mp = mp
|
14 |
+
mp._mp = mp
|
15 |
+
iv._mp = mp
|
16 |
+
mp._fp = fp
|
17 |
+
fp._fp = fp
|
18 |
+
mp._iv = iv
|
19 |
+
fp._iv = iv
|
20 |
+
iv._iv = iv
|
21 |
+
|
22 |
+
# XXX: extremely bad pickle hack
|
23 |
+
from . import ctx_mp as _ctx_mp
|
24 |
+
_ctx_mp._mpf_module.mpf = mp.mpf
|
25 |
+
_ctx_mp._mpf_module.mpc = mp.mpc
|
26 |
+
|
27 |
+
make_mpf = mp.make_mpf
|
28 |
+
make_mpc = mp.make_mpc
|
29 |
+
|
30 |
+
extraprec = mp.extraprec
|
31 |
+
extradps = mp.extradps
|
32 |
+
workprec = mp.workprec
|
33 |
+
workdps = mp.workdps
|
34 |
+
autoprec = mp.autoprec
|
35 |
+
maxcalls = mp.maxcalls
|
36 |
+
memoize = mp.memoize
|
37 |
+
|
38 |
+
mag = mp.mag
|
39 |
+
|
40 |
+
bernfrac = mp.bernfrac
|
41 |
+
|
42 |
+
qfrom = mp.qfrom
|
43 |
+
mfrom = mp.mfrom
|
44 |
+
kfrom = mp.kfrom
|
45 |
+
taufrom = mp.taufrom
|
46 |
+
qbarfrom = mp.qbarfrom
|
47 |
+
ellipfun = mp.ellipfun
|
48 |
+
jtheta = mp.jtheta
|
49 |
+
kleinj = mp.kleinj
|
50 |
+
eta = mp.eta
|
51 |
+
|
52 |
+
qp = mp.qp
|
53 |
+
qhyper = mp.qhyper
|
54 |
+
qgamma = mp.qgamma
|
55 |
+
qfac = mp.qfac
|
56 |
+
|
57 |
+
nint_distance = mp.nint_distance
|
58 |
+
|
59 |
+
plot = mp.plot
|
60 |
+
cplot = mp.cplot
|
61 |
+
splot = mp.splot
|
62 |
+
|
63 |
+
odefun = mp.odefun
|
64 |
+
|
65 |
+
jacobian = mp.jacobian
|
66 |
+
findroot = mp.findroot
|
67 |
+
multiplicity = mp.multiplicity
|
68 |
+
|
69 |
+
isinf = mp.isinf
|
70 |
+
isnan = mp.isnan
|
71 |
+
isnormal = mp.isnormal
|
72 |
+
isint = mp.isint
|
73 |
+
isfinite = mp.isfinite
|
74 |
+
almosteq = mp.almosteq
|
75 |
+
nan = mp.nan
|
76 |
+
rand = mp.rand
|
77 |
+
|
78 |
+
absmin = mp.absmin
|
79 |
+
absmax = mp.absmax
|
80 |
+
|
81 |
+
fraction = mp.fraction
|
82 |
+
|
83 |
+
linspace = mp.linspace
|
84 |
+
arange = mp.arange
|
85 |
+
|
86 |
+
mpmathify = convert = mp.convert
|
87 |
+
mpc = mp.mpc
|
88 |
+
|
89 |
+
mpi = iv._mpi
|
90 |
+
|
91 |
+
nstr = mp.nstr
|
92 |
+
nprint = mp.nprint
|
93 |
+
chop = mp.chop
|
94 |
+
|
95 |
+
fneg = mp.fneg
|
96 |
+
fadd = mp.fadd
|
97 |
+
fsub = mp.fsub
|
98 |
+
fmul = mp.fmul
|
99 |
+
fdiv = mp.fdiv
|
100 |
+
fprod = mp.fprod
|
101 |
+
|
102 |
+
quad = mp.quad
|
103 |
+
quadgl = mp.quadgl
|
104 |
+
quadts = mp.quadts
|
105 |
+
quadosc = mp.quadosc
|
106 |
+
quadsubdiv = mp.quadsubdiv
|
107 |
+
|
108 |
+
invertlaplace = mp.invertlaplace
|
109 |
+
invlaptalbot = mp.invlaptalbot
|
110 |
+
invlapstehfest = mp.invlapstehfest
|
111 |
+
invlapdehoog = mp.invlapdehoog
|
112 |
+
|
113 |
+
pslq = mp.pslq
|
114 |
+
identify = mp.identify
|
115 |
+
findpoly = mp.findpoly
|
116 |
+
|
117 |
+
richardson = mp.richardson
|
118 |
+
shanks = mp.shanks
|
119 |
+
levin = mp.levin
|
120 |
+
cohen_alt = mp.cohen_alt
|
121 |
+
nsum = mp.nsum
|
122 |
+
nprod = mp.nprod
|
123 |
+
difference = mp.difference
|
124 |
+
diff = mp.diff
|
125 |
+
diffs = mp.diffs
|
126 |
+
diffs_prod = mp.diffs_prod
|
127 |
+
diffs_exp = mp.diffs_exp
|
128 |
+
diffun = mp.diffun
|
129 |
+
differint = mp.differint
|
130 |
+
taylor = mp.taylor
|
131 |
+
pade = mp.pade
|
132 |
+
polyval = mp.polyval
|
133 |
+
polyroots = mp.polyroots
|
134 |
+
fourier = mp.fourier
|
135 |
+
fourierval = mp.fourierval
|
136 |
+
sumem = mp.sumem
|
137 |
+
sumap = mp.sumap
|
138 |
+
chebyfit = mp.chebyfit
|
139 |
+
limit = mp.limit
|
140 |
+
|
141 |
+
matrix = mp.matrix
|
142 |
+
eye = mp.eye
|
143 |
+
diag = mp.diag
|
144 |
+
zeros = mp.zeros
|
145 |
+
ones = mp.ones
|
146 |
+
hilbert = mp.hilbert
|
147 |
+
randmatrix = mp.randmatrix
|
148 |
+
swap_row = mp.swap_row
|
149 |
+
extend = mp.extend
|
150 |
+
norm = mp.norm
|
151 |
+
mnorm = mp.mnorm
|
152 |
+
|
153 |
+
lu_solve = mp.lu_solve
|
154 |
+
lu = mp.lu
|
155 |
+
qr = mp.qr
|
156 |
+
unitvector = mp.unitvector
|
157 |
+
inverse = mp.inverse
|
158 |
+
residual = mp.residual
|
159 |
+
qr_solve = mp.qr_solve
|
160 |
+
cholesky = mp.cholesky
|
161 |
+
cholesky_solve = mp.cholesky_solve
|
162 |
+
det = mp.det
|
163 |
+
cond = mp.cond
|
164 |
+
hessenberg = mp.hessenberg
|
165 |
+
schur = mp.schur
|
166 |
+
eig = mp.eig
|
167 |
+
eig_sort = mp.eig_sort
|
168 |
+
eigsy = mp.eigsy
|
169 |
+
eighe = mp.eighe
|
170 |
+
eigh = mp.eigh
|
171 |
+
svd_r = mp.svd_r
|
172 |
+
svd_c = mp.svd_c
|
173 |
+
svd = mp.svd
|
174 |
+
gauss_quadrature = mp.gauss_quadrature
|
175 |
+
|
176 |
+
expm = mp.expm
|
177 |
+
sqrtm = mp.sqrtm
|
178 |
+
powm = mp.powm
|
179 |
+
logm = mp.logm
|
180 |
+
sinm = mp.sinm
|
181 |
+
cosm = mp.cosm
|
182 |
+
|
183 |
+
mpf = mp.mpf
|
184 |
+
j = mp.j
|
185 |
+
exp = mp.exp
|
186 |
+
expj = mp.expj
|
187 |
+
expjpi = mp.expjpi
|
188 |
+
ln = mp.ln
|
189 |
+
im = mp.im
|
190 |
+
re = mp.re
|
191 |
+
inf = mp.inf
|
192 |
+
ninf = mp.ninf
|
193 |
+
sign = mp.sign
|
194 |
+
|
195 |
+
eps = mp.eps
|
196 |
+
pi = mp.pi
|
197 |
+
ln2 = mp.ln2
|
198 |
+
ln10 = mp.ln10
|
199 |
+
phi = mp.phi
|
200 |
+
e = mp.e
|
201 |
+
euler = mp.euler
|
202 |
+
catalan = mp.catalan
|
203 |
+
khinchin = mp.khinchin
|
204 |
+
glaisher = mp.glaisher
|
205 |
+
apery = mp.apery
|
206 |
+
degree = mp.degree
|
207 |
+
twinprime = mp.twinprime
|
208 |
+
mertens = mp.mertens
|
209 |
+
|
210 |
+
ldexp = mp.ldexp
|
211 |
+
frexp = mp.frexp
|
212 |
+
|
213 |
+
fsum = mp.fsum
|
214 |
+
fdot = mp.fdot
|
215 |
+
|
216 |
+
sqrt = mp.sqrt
|
217 |
+
cbrt = mp.cbrt
|
218 |
+
exp = mp.exp
|
219 |
+
ln = mp.ln
|
220 |
+
log = mp.log
|
221 |
+
log10 = mp.log10
|
222 |
+
power = mp.power
|
223 |
+
cos = mp.cos
|
224 |
+
sin = mp.sin
|
225 |
+
tan = mp.tan
|
226 |
+
cosh = mp.cosh
|
227 |
+
sinh = mp.sinh
|
228 |
+
tanh = mp.tanh
|
229 |
+
acos = mp.acos
|
230 |
+
asin = mp.asin
|
231 |
+
atan = mp.atan
|
232 |
+
asinh = mp.asinh
|
233 |
+
acosh = mp.acosh
|
234 |
+
atanh = mp.atanh
|
235 |
+
sec = mp.sec
|
236 |
+
csc = mp.csc
|
237 |
+
cot = mp.cot
|
238 |
+
sech = mp.sech
|
239 |
+
csch = mp.csch
|
240 |
+
coth = mp.coth
|
241 |
+
asec = mp.asec
|
242 |
+
acsc = mp.acsc
|
243 |
+
acot = mp.acot
|
244 |
+
asech = mp.asech
|
245 |
+
acsch = mp.acsch
|
246 |
+
acoth = mp.acoth
|
247 |
+
cospi = mp.cospi
|
248 |
+
sinpi = mp.sinpi
|
249 |
+
sinc = mp.sinc
|
250 |
+
sincpi = mp.sincpi
|
251 |
+
cos_sin = mp.cos_sin
|
252 |
+
cospi_sinpi = mp.cospi_sinpi
|
253 |
+
fabs = mp.fabs
|
254 |
+
re = mp.re
|
255 |
+
im = mp.im
|
256 |
+
conj = mp.conj
|
257 |
+
floor = mp.floor
|
258 |
+
ceil = mp.ceil
|
259 |
+
nint = mp.nint
|
260 |
+
frac = mp.frac
|
261 |
+
root = mp.root
|
262 |
+
nthroot = mp.nthroot
|
263 |
+
hypot = mp.hypot
|
264 |
+
fmod = mp.fmod
|
265 |
+
ldexp = mp.ldexp
|
266 |
+
frexp = mp.frexp
|
267 |
+
sign = mp.sign
|
268 |
+
arg = mp.arg
|
269 |
+
phase = mp.phase
|
270 |
+
polar = mp.polar
|
271 |
+
rect = mp.rect
|
272 |
+
degrees = mp.degrees
|
273 |
+
radians = mp.radians
|
274 |
+
atan2 = mp.atan2
|
275 |
+
fib = mp.fib
|
276 |
+
fibonacci = mp.fibonacci
|
277 |
+
lambertw = mp.lambertw
|
278 |
+
zeta = mp.zeta
|
279 |
+
altzeta = mp.altzeta
|
280 |
+
gamma = mp.gamma
|
281 |
+
rgamma = mp.rgamma
|
282 |
+
factorial = mp.factorial
|
283 |
+
fac = mp.fac
|
284 |
+
fac2 = mp.fac2
|
285 |
+
beta = mp.beta
|
286 |
+
betainc = mp.betainc
|
287 |
+
psi = mp.psi
|
288 |
+
#psi0 = mp.psi0
|
289 |
+
#psi1 = mp.psi1
|
290 |
+
#psi2 = mp.psi2
|
291 |
+
#psi3 = mp.psi3
|
292 |
+
polygamma = mp.polygamma
|
293 |
+
digamma = mp.digamma
|
294 |
+
#trigamma = mp.trigamma
|
295 |
+
#tetragamma = mp.tetragamma
|
296 |
+
#pentagamma = mp.pentagamma
|
297 |
+
harmonic = mp.harmonic
|
298 |
+
bernoulli = mp.bernoulli
|
299 |
+
bernfrac = mp.bernfrac
|
300 |
+
stieltjes = mp.stieltjes
|
301 |
+
hurwitz = mp.hurwitz
|
302 |
+
dirichlet = mp.dirichlet
|
303 |
+
bernpoly = mp.bernpoly
|
304 |
+
eulerpoly = mp.eulerpoly
|
305 |
+
eulernum = mp.eulernum
|
306 |
+
polylog = mp.polylog
|
307 |
+
clsin = mp.clsin
|
308 |
+
clcos = mp.clcos
|
309 |
+
gammainc = mp.gammainc
|
310 |
+
gammaprod = mp.gammaprod
|
311 |
+
binomial = mp.binomial
|
312 |
+
rf = mp.rf
|
313 |
+
ff = mp.ff
|
314 |
+
hyper = mp.hyper
|
315 |
+
hyp0f1 = mp.hyp0f1
|
316 |
+
hyp1f1 = mp.hyp1f1
|
317 |
+
hyp1f2 = mp.hyp1f2
|
318 |
+
hyp2f1 = mp.hyp2f1
|
319 |
+
hyp2f2 = mp.hyp2f2
|
320 |
+
hyp2f0 = mp.hyp2f0
|
321 |
+
hyp2f3 = mp.hyp2f3
|
322 |
+
hyp3f2 = mp.hyp3f2
|
323 |
+
hyperu = mp.hyperu
|
324 |
+
hypercomb = mp.hypercomb
|
325 |
+
meijerg = mp.meijerg
|
326 |
+
appellf1 = mp.appellf1
|
327 |
+
appellf2 = mp.appellf2
|
328 |
+
appellf3 = mp.appellf3
|
329 |
+
appellf4 = mp.appellf4
|
330 |
+
hyper2d = mp.hyper2d
|
331 |
+
bihyper = mp.bihyper
|
332 |
+
erf = mp.erf
|
333 |
+
erfc = mp.erfc
|
334 |
+
erfi = mp.erfi
|
335 |
+
erfinv = mp.erfinv
|
336 |
+
npdf = mp.npdf
|
337 |
+
ncdf = mp.ncdf
|
338 |
+
expint = mp.expint
|
339 |
+
e1 = mp.e1
|
340 |
+
ei = mp.ei
|
341 |
+
li = mp.li
|
342 |
+
ci = mp.ci
|
343 |
+
si = mp.si
|
344 |
+
chi = mp.chi
|
345 |
+
shi = mp.shi
|
346 |
+
fresnels = mp.fresnels
|
347 |
+
fresnelc = mp.fresnelc
|
348 |
+
airyai = mp.airyai
|
349 |
+
airybi = mp.airybi
|
350 |
+
airyaizero = mp.airyaizero
|
351 |
+
airybizero = mp.airybizero
|
352 |
+
scorergi = mp.scorergi
|
353 |
+
scorerhi = mp.scorerhi
|
354 |
+
ellipk = mp.ellipk
|
355 |
+
ellipe = mp.ellipe
|
356 |
+
ellipf = mp.ellipf
|
357 |
+
ellippi = mp.ellippi
|
358 |
+
elliprc = mp.elliprc
|
359 |
+
elliprj = mp.elliprj
|
360 |
+
elliprf = mp.elliprf
|
361 |
+
elliprd = mp.elliprd
|
362 |
+
elliprg = mp.elliprg
|
363 |
+
agm = mp.agm
|
364 |
+
jacobi = mp.jacobi
|
365 |
+
chebyt = mp.chebyt
|
366 |
+
chebyu = mp.chebyu
|
367 |
+
legendre = mp.legendre
|
368 |
+
legenp = mp.legenp
|
369 |
+
legenq = mp.legenq
|
370 |
+
hermite = mp.hermite
|
371 |
+
pcfd = mp.pcfd
|
372 |
+
pcfu = mp.pcfu
|
373 |
+
pcfv = mp.pcfv
|
374 |
+
pcfw = mp.pcfw
|
375 |
+
gegenbauer = mp.gegenbauer
|
376 |
+
laguerre = mp.laguerre
|
377 |
+
spherharm = mp.spherharm
|
378 |
+
besselj = mp.besselj
|
379 |
+
j0 = mp.j0
|
380 |
+
j1 = mp.j1
|
381 |
+
besseli = mp.besseli
|
382 |
+
bessely = mp.bessely
|
383 |
+
besselk = mp.besselk
|
384 |
+
besseljzero = mp.besseljzero
|
385 |
+
besselyzero = mp.besselyzero
|
386 |
+
hankel1 = mp.hankel1
|
387 |
+
hankel2 = mp.hankel2
|
388 |
+
struveh = mp.struveh
|
389 |
+
struvel = mp.struvel
|
390 |
+
angerj = mp.angerj
|
391 |
+
webere = mp.webere
|
392 |
+
lommels1 = mp.lommels1
|
393 |
+
lommels2 = mp.lommels2
|
394 |
+
whitm = mp.whitm
|
395 |
+
whitw = mp.whitw
|
396 |
+
ber = mp.ber
|
397 |
+
bei = mp.bei
|
398 |
+
ker = mp.ker
|
399 |
+
kei = mp.kei
|
400 |
+
coulombc = mp.coulombc
|
401 |
+
coulombf = mp.coulombf
|
402 |
+
coulombg = mp.coulombg
|
403 |
+
barnesg = mp.barnesg
|
404 |
+
superfac = mp.superfac
|
405 |
+
hyperfac = mp.hyperfac
|
406 |
+
loggamma = mp.loggamma
|
407 |
+
siegeltheta = mp.siegeltheta
|
408 |
+
siegelz = mp.siegelz
|
409 |
+
grampoint = mp.grampoint
|
410 |
+
zetazero = mp.zetazero
|
411 |
+
riemannr = mp.riemannr
|
412 |
+
primepi = mp.primepi
|
413 |
+
primepi2 = mp.primepi2
|
414 |
+
primezeta = mp.primezeta
|
415 |
+
bell = mp.bell
|
416 |
+
polyexp = mp.polyexp
|
417 |
+
expm1 = mp.expm1
|
418 |
+
log1p = mp.log1p
|
419 |
+
powm1 = mp.powm1
|
420 |
+
unitroots = mp.unitroots
|
421 |
+
cyclotomic = mp.cyclotomic
|
422 |
+
mangoldt = mp.mangoldt
|
423 |
+
secondzeta = mp.secondzeta
|
424 |
+
nzeros = mp.nzeros
|
425 |
+
backlunds = mp.backlunds
|
426 |
+
lerchphi = mp.lerchphi
|
427 |
+
stirling1 = mp.stirling1
|
428 |
+
stirling2 = mp.stirling2
|
429 |
+
squarew = mp.squarew
|
430 |
+
trianglew = mp.trianglew
|
431 |
+
sawtoothw = mp.sawtoothw
|
432 |
+
unit_triangle = mp.unit_triangle
|
433 |
+
sigmoid = mp.sigmoid
|
434 |
+
|
435 |
+
# be careful when changing this name, don't use test*!
|
436 |
+
def runtests():
|
437 |
+
"""
|
438 |
+
Run all mpmath tests and print output.
|
439 |
+
"""
|
440 |
+
import os.path
|
441 |
+
from inspect import getsourcefile
|
442 |
+
from .tests import runtests as tests
|
443 |
+
testdir = os.path.dirname(os.path.abspath(getsourcefile(tests)))
|
444 |
+
importdir = os.path.abspath(testdir + '/../..')
|
445 |
+
tests.testit(importdir, testdir)
|
446 |
+
|
447 |
+
def doctests(filter=[]):
|
448 |
+
import sys
|
449 |
+
from timeit import default_timer as clock
|
450 |
+
for i, arg in enumerate(sys.argv):
|
451 |
+
if '__init__.py' in arg:
|
452 |
+
filter = [sn for sn in sys.argv[i+1:] if not sn.startswith("-")]
|
453 |
+
break
|
454 |
+
import doctest
|
455 |
+
globs = globals().copy()
|
456 |
+
for obj in globs: #sorted(globs.keys()):
|
457 |
+
if filter:
|
458 |
+
if not sum([pat in obj for pat in filter]):
|
459 |
+
continue
|
460 |
+
sys.stdout.write(str(obj) + " ")
|
461 |
+
sys.stdout.flush()
|
462 |
+
t1 = clock()
|
463 |
+
doctest.run_docstring_examples(globs[obj], {}, verbose=("-v" in sys.argv))
|
464 |
+
t2 = clock()
|
465 |
+
print(round(t2-t1, 3))
|
466 |
+
|
467 |
+
if __name__ == '__main__':
|
468 |
+
doctests()
|
env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/ctx_mp_python.cpython-310.pyc
ADDED
Binary file (34.6 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/__pycache__/function_docs.cpython-310.pyc
ADDED
Binary file (284 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/ctx_fp.py
ADDED
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .ctx_base import StandardBaseContext
|
2 |
+
|
3 |
+
import math
|
4 |
+
import cmath
|
5 |
+
from . import math2
|
6 |
+
|
7 |
+
from . import function_docs
|
8 |
+
|
9 |
+
from .libmp import mpf_bernoulli, to_float, int_types
|
10 |
+
from . import libmp
|
11 |
+
|
12 |
+
class FPContext(StandardBaseContext):
|
13 |
+
"""
|
14 |
+
Context for fast low-precision arithmetic (53-bit precision, giving at most
|
15 |
+
about 15-digit accuracy), using Python's builtin float and complex.
|
16 |
+
"""
|
17 |
+
|
18 |
+
def __init__(ctx):
|
19 |
+
StandardBaseContext.__init__(ctx)
|
20 |
+
|
21 |
+
# Override SpecialFunctions implementation
|
22 |
+
ctx.loggamma = math2.loggamma
|
23 |
+
ctx._bernoulli_cache = {}
|
24 |
+
ctx.pretty = False
|
25 |
+
|
26 |
+
ctx._init_aliases()
|
27 |
+
|
28 |
+
_mpq = lambda cls, x: float(x[0])/x[1]
|
29 |
+
|
30 |
+
NoConvergence = libmp.NoConvergence
|
31 |
+
|
32 |
+
def _get_prec(ctx): return 53
|
33 |
+
def _set_prec(ctx, p): return
|
34 |
+
def _get_dps(ctx): return 15
|
35 |
+
def _set_dps(ctx, p): return
|
36 |
+
|
37 |
+
_fixed_precision = True
|
38 |
+
|
39 |
+
prec = property(_get_prec, _set_prec)
|
40 |
+
dps = property(_get_dps, _set_dps)
|
41 |
+
|
42 |
+
zero = 0.0
|
43 |
+
one = 1.0
|
44 |
+
eps = math2.EPS
|
45 |
+
inf = math2.INF
|
46 |
+
ninf = math2.NINF
|
47 |
+
nan = math2.NAN
|
48 |
+
j = 1j
|
49 |
+
|
50 |
+
# Called by SpecialFunctions.__init__()
|
51 |
+
@classmethod
|
52 |
+
def _wrap_specfun(cls, name, f, wrap):
|
53 |
+
if wrap:
|
54 |
+
def f_wrapped(ctx, *args, **kwargs):
|
55 |
+
convert = ctx.convert
|
56 |
+
args = [convert(a) for a in args]
|
57 |
+
return f(ctx, *args, **kwargs)
|
58 |
+
else:
|
59 |
+
f_wrapped = f
|
60 |
+
f_wrapped.__doc__ = function_docs.__dict__.get(name, f.__doc__)
|
61 |
+
setattr(cls, name, f_wrapped)
|
62 |
+
|
63 |
+
def bernoulli(ctx, n):
|
64 |
+
cache = ctx._bernoulli_cache
|
65 |
+
if n in cache:
|
66 |
+
return cache[n]
|
67 |
+
cache[n] = to_float(mpf_bernoulli(n, 53, 'n'), strict=True)
|
68 |
+
return cache[n]
|
69 |
+
|
70 |
+
pi = math2.pi
|
71 |
+
e = math2.e
|
72 |
+
euler = math2.euler
|
73 |
+
sqrt2 = 1.4142135623730950488
|
74 |
+
sqrt5 = 2.2360679774997896964
|
75 |
+
phi = 1.6180339887498948482
|
76 |
+
ln2 = 0.69314718055994530942
|
77 |
+
ln10 = 2.302585092994045684
|
78 |
+
euler = 0.57721566490153286061
|
79 |
+
catalan = 0.91596559417721901505
|
80 |
+
khinchin = 2.6854520010653064453
|
81 |
+
apery = 1.2020569031595942854
|
82 |
+
glaisher = 1.2824271291006226369
|
83 |
+
|
84 |
+
absmin = absmax = abs
|
85 |
+
|
86 |
+
def is_special(ctx, x):
|
87 |
+
return x - x != 0.0
|
88 |
+
|
89 |
+
def isnan(ctx, x):
|
90 |
+
return x != x
|
91 |
+
|
92 |
+
def isinf(ctx, x):
|
93 |
+
return abs(x) == math2.INF
|
94 |
+
|
95 |
+
def isnormal(ctx, x):
|
96 |
+
if x:
|
97 |
+
return x - x == 0.0
|
98 |
+
return False
|
99 |
+
|
100 |
+
def isnpint(ctx, x):
|
101 |
+
if type(x) is complex:
|
102 |
+
if x.imag:
|
103 |
+
return False
|
104 |
+
x = x.real
|
105 |
+
return x <= 0.0 and round(x) == x
|
106 |
+
|
107 |
+
mpf = float
|
108 |
+
mpc = complex
|
109 |
+
|
110 |
+
def convert(ctx, x):
|
111 |
+
try:
|
112 |
+
return float(x)
|
113 |
+
except:
|
114 |
+
return complex(x)
|
115 |
+
|
116 |
+
power = staticmethod(math2.pow)
|
117 |
+
sqrt = staticmethod(math2.sqrt)
|
118 |
+
exp = staticmethod(math2.exp)
|
119 |
+
ln = log = staticmethod(math2.log)
|
120 |
+
cos = staticmethod(math2.cos)
|
121 |
+
sin = staticmethod(math2.sin)
|
122 |
+
tan = staticmethod(math2.tan)
|
123 |
+
cos_sin = staticmethod(math2.cos_sin)
|
124 |
+
acos = staticmethod(math2.acos)
|
125 |
+
asin = staticmethod(math2.asin)
|
126 |
+
atan = staticmethod(math2.atan)
|
127 |
+
cosh = staticmethod(math2.cosh)
|
128 |
+
sinh = staticmethod(math2.sinh)
|
129 |
+
tanh = staticmethod(math2.tanh)
|
130 |
+
gamma = staticmethod(math2.gamma)
|
131 |
+
rgamma = staticmethod(math2.rgamma)
|
132 |
+
fac = factorial = staticmethod(math2.factorial)
|
133 |
+
floor = staticmethod(math2.floor)
|
134 |
+
ceil = staticmethod(math2.ceil)
|
135 |
+
cospi = staticmethod(math2.cospi)
|
136 |
+
sinpi = staticmethod(math2.sinpi)
|
137 |
+
cbrt = staticmethod(math2.cbrt)
|
138 |
+
_nthroot = staticmethod(math2.nthroot)
|
139 |
+
_ei = staticmethod(math2.ei)
|
140 |
+
_e1 = staticmethod(math2.e1)
|
141 |
+
_zeta = _zeta_int = staticmethod(math2.zeta)
|
142 |
+
|
143 |
+
# XXX: math2
|
144 |
+
def arg(ctx, z):
|
145 |
+
z = complex(z)
|
146 |
+
return math.atan2(z.imag, z.real)
|
147 |
+
|
148 |
+
def expj(ctx, x):
|
149 |
+
return ctx.exp(ctx.j*x)
|
150 |
+
|
151 |
+
def expjpi(ctx, x):
|
152 |
+
return ctx.exp(ctx.j*ctx.pi*x)
|
153 |
+
|
154 |
+
ldexp = math.ldexp
|
155 |
+
frexp = math.frexp
|
156 |
+
|
157 |
+
def mag(ctx, z):
|
158 |
+
if z:
|
159 |
+
return ctx.frexp(abs(z))[1]
|
160 |
+
return ctx.ninf
|
161 |
+
|
162 |
+
def isint(ctx, z):
|
163 |
+
if hasattr(z, "imag"): # float/int don't have .real/.imag in py2.5
|
164 |
+
if z.imag:
|
165 |
+
return False
|
166 |
+
z = z.real
|
167 |
+
try:
|
168 |
+
return z == int(z)
|
169 |
+
except:
|
170 |
+
return False
|
171 |
+
|
172 |
+
def nint_distance(ctx, z):
|
173 |
+
if hasattr(z, "imag"): # float/int don't have .real/.imag in py2.5
|
174 |
+
n = round(z.real)
|
175 |
+
else:
|
176 |
+
n = round(z)
|
177 |
+
if n == z:
|
178 |
+
return n, ctx.ninf
|
179 |
+
return n, ctx.mag(abs(z-n))
|
180 |
+
|
181 |
+
def _convert_param(ctx, z):
|
182 |
+
if type(z) is tuple:
|
183 |
+
p, q = z
|
184 |
+
return ctx.mpf(p) / q, 'R'
|
185 |
+
if hasattr(z, "imag"): # float/int don't have .real/.imag in py2.5
|
186 |
+
intz = int(z.real)
|
187 |
+
else:
|
188 |
+
intz = int(z)
|
189 |
+
if z == intz:
|
190 |
+
return intz, 'Z'
|
191 |
+
return z, 'R'
|
192 |
+
|
193 |
+
def _is_real_type(ctx, z):
|
194 |
+
return isinstance(z, float) or isinstance(z, int_types)
|
195 |
+
|
196 |
+
def _is_complex_type(ctx, z):
|
197 |
+
return isinstance(z, complex)
|
198 |
+
|
199 |
+
def hypsum(ctx, p, q, types, coeffs, z, maxterms=6000, **kwargs):
|
200 |
+
coeffs = list(coeffs)
|
201 |
+
num = range(p)
|
202 |
+
den = range(p,p+q)
|
203 |
+
tol = ctx.eps
|
204 |
+
s = t = 1.0
|
205 |
+
k = 0
|
206 |
+
while 1:
|
207 |
+
for i in num: t *= (coeffs[i]+k)
|
208 |
+
for i in den: t /= (coeffs[i]+k)
|
209 |
+
k += 1; t /= k; t *= z; s += t
|
210 |
+
if abs(t) < tol:
|
211 |
+
return s
|
212 |
+
if k > maxterms:
|
213 |
+
raise ctx.NoConvergence
|
214 |
+
|
215 |
+
def atan2(ctx, x, y):
|
216 |
+
return math.atan2(x, y)
|
217 |
+
|
218 |
+
def psi(ctx, m, z):
|
219 |
+
m = int(m)
|
220 |
+
if m == 0:
|
221 |
+
return ctx.digamma(z)
|
222 |
+
return (-1)**(m+1) * ctx.fac(m) * ctx.zeta(m+1, z)
|
223 |
+
|
224 |
+
digamma = staticmethod(math2.digamma)
|
225 |
+
|
226 |
+
def harmonic(ctx, x):
|
227 |
+
x = ctx.convert(x)
|
228 |
+
if x == 0 or x == 1:
|
229 |
+
return x
|
230 |
+
return ctx.digamma(x+1) + ctx.euler
|
231 |
+
|
232 |
+
nstr = str
|
233 |
+
|
234 |
+
def to_fixed(ctx, x, prec):
|
235 |
+
return int(math.ldexp(x, prec))
|
236 |
+
|
237 |
+
def rand(ctx):
|
238 |
+
import random
|
239 |
+
return random.random()
|
240 |
+
|
241 |
+
_erf = staticmethod(math2.erf)
|
242 |
+
_erfc = staticmethod(math2.erfc)
|
243 |
+
|
244 |
+
def sum_accurately(ctx, terms, check_step=1):
|
245 |
+
s = ctx.zero
|
246 |
+
k = 0
|
247 |
+
for term in terms():
|
248 |
+
s += term
|
249 |
+
if (not k % check_step) and term:
|
250 |
+
if abs(term) <= 1e-18*abs(s):
|
251 |
+
break
|
252 |
+
k += 1
|
253 |
+
return s
|
env-llmeval/lib/python3.10/site-packages/mpmath/ctx_iv.py
ADDED
@@ -0,0 +1,551 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import operator
|
2 |
+
|
3 |
+
from . import libmp
|
4 |
+
|
5 |
+
from .libmp.backend import basestring
|
6 |
+
|
7 |
+
from .libmp import (
|
8 |
+
int_types, MPZ_ONE,
|
9 |
+
prec_to_dps, dps_to_prec, repr_dps,
|
10 |
+
round_floor, round_ceiling,
|
11 |
+
fzero, finf, fninf, fnan,
|
12 |
+
mpf_le, mpf_neg,
|
13 |
+
from_int, from_float, from_str, from_rational,
|
14 |
+
mpi_mid, mpi_delta, mpi_str,
|
15 |
+
mpi_abs, mpi_pos, mpi_neg, mpi_add, mpi_sub,
|
16 |
+
mpi_mul, mpi_div, mpi_pow_int, mpi_pow,
|
17 |
+
mpi_from_str,
|
18 |
+
mpci_pos, mpci_neg, mpci_add, mpci_sub, mpci_mul, mpci_div, mpci_pow,
|
19 |
+
mpci_abs, mpci_pow, mpci_exp, mpci_log,
|
20 |
+
ComplexResult,
|
21 |
+
mpf_hash, mpc_hash)
|
22 |
+
from .matrices.matrices import _matrix
|
23 |
+
|
24 |
+
mpi_zero = (fzero, fzero)
|
25 |
+
|
26 |
+
from .ctx_base import StandardBaseContext
|
27 |
+
|
28 |
+
new = object.__new__
|
29 |
+
|
30 |
+
def convert_mpf_(x, prec, rounding):
|
31 |
+
if hasattr(x, "_mpf_"): return x._mpf_
|
32 |
+
if isinstance(x, int_types): return from_int(x, prec, rounding)
|
33 |
+
if isinstance(x, float): return from_float(x, prec, rounding)
|
34 |
+
if isinstance(x, basestring): return from_str(x, prec, rounding)
|
35 |
+
raise NotImplementedError
|
36 |
+
|
37 |
+
|
38 |
+
class ivmpf(object):
|
39 |
+
"""
|
40 |
+
Interval arithmetic class. Precision is controlled by iv.prec.
|
41 |
+
"""
|
42 |
+
|
43 |
+
def __new__(cls, x=0):
|
44 |
+
return cls.ctx.convert(x)
|
45 |
+
|
46 |
+
def cast(self, cls, f_convert):
|
47 |
+
a, b = self._mpi_
|
48 |
+
if a == b:
|
49 |
+
return cls(f_convert(a))
|
50 |
+
raise ValueError
|
51 |
+
|
52 |
+
def __int__(self):
|
53 |
+
return self.cast(int, libmp.to_int)
|
54 |
+
|
55 |
+
def __float__(self):
|
56 |
+
return self.cast(float, libmp.to_float)
|
57 |
+
|
58 |
+
def __complex__(self):
|
59 |
+
return self.cast(complex, libmp.to_float)
|
60 |
+
|
61 |
+
def __hash__(self):
|
62 |
+
a, b = self._mpi_
|
63 |
+
if a == b:
|
64 |
+
return mpf_hash(a)
|
65 |
+
else:
|
66 |
+
return hash(self._mpi_)
|
67 |
+
|
68 |
+
@property
|
69 |
+
def real(self): return self
|
70 |
+
|
71 |
+
@property
|
72 |
+
def imag(self): return self.ctx.zero
|
73 |
+
|
74 |
+
def conjugate(self): return self
|
75 |
+
|
76 |
+
@property
|
77 |
+
def a(self):
|
78 |
+
a, b = self._mpi_
|
79 |
+
return self.ctx.make_mpf((a, a))
|
80 |
+
|
81 |
+
@property
|
82 |
+
def b(self):
|
83 |
+
a, b = self._mpi_
|
84 |
+
return self.ctx.make_mpf((b, b))
|
85 |
+
|
86 |
+
@property
|
87 |
+
def mid(self):
|
88 |
+
ctx = self.ctx
|
89 |
+
v = mpi_mid(self._mpi_, ctx.prec)
|
90 |
+
return ctx.make_mpf((v, v))
|
91 |
+
|
92 |
+
@property
|
93 |
+
def delta(self):
|
94 |
+
ctx = self.ctx
|
95 |
+
v = mpi_delta(self._mpi_, ctx.prec)
|
96 |
+
return ctx.make_mpf((v,v))
|
97 |
+
|
98 |
+
@property
|
99 |
+
def _mpci_(self):
|
100 |
+
return self._mpi_, mpi_zero
|
101 |
+
|
102 |
+
def _compare(*args):
|
103 |
+
raise TypeError("no ordering relation is defined for intervals")
|
104 |
+
|
105 |
+
__gt__ = _compare
|
106 |
+
__le__ = _compare
|
107 |
+
__gt__ = _compare
|
108 |
+
__ge__ = _compare
|
109 |
+
|
110 |
+
def __contains__(self, t):
|
111 |
+
t = self.ctx.mpf(t)
|
112 |
+
return (self.a <= t.a) and (t.b <= self.b)
|
113 |
+
|
114 |
+
def __str__(self):
|
115 |
+
return mpi_str(self._mpi_, self.ctx.prec)
|
116 |
+
|
117 |
+
def __repr__(self):
|
118 |
+
if self.ctx.pretty:
|
119 |
+
return str(self)
|
120 |
+
a, b = self._mpi_
|
121 |
+
n = repr_dps(self.ctx.prec)
|
122 |
+
a = libmp.to_str(a, n)
|
123 |
+
b = libmp.to_str(b, n)
|
124 |
+
return "mpi(%r, %r)" % (a, b)
|
125 |
+
|
126 |
+
def _compare(s, t, cmpfun):
|
127 |
+
if not hasattr(t, "_mpi_"):
|
128 |
+
try:
|
129 |
+
t = s.ctx.convert(t)
|
130 |
+
except:
|
131 |
+
return NotImplemented
|
132 |
+
return cmpfun(s._mpi_, t._mpi_)
|
133 |
+
|
134 |
+
def __eq__(s, t): return s._compare(t, libmp.mpi_eq)
|
135 |
+
def __ne__(s, t): return s._compare(t, libmp.mpi_ne)
|
136 |
+
def __lt__(s, t): return s._compare(t, libmp.mpi_lt)
|
137 |
+
def __le__(s, t): return s._compare(t, libmp.mpi_le)
|
138 |
+
def __gt__(s, t): return s._compare(t, libmp.mpi_gt)
|
139 |
+
def __ge__(s, t): return s._compare(t, libmp.mpi_ge)
|
140 |
+
|
141 |
+
def __abs__(self):
|
142 |
+
return self.ctx.make_mpf(mpi_abs(self._mpi_, self.ctx.prec))
|
143 |
+
def __pos__(self):
|
144 |
+
return self.ctx.make_mpf(mpi_pos(self._mpi_, self.ctx.prec))
|
145 |
+
def __neg__(self):
|
146 |
+
return self.ctx.make_mpf(mpi_neg(self._mpi_, self.ctx.prec))
|
147 |
+
|
148 |
+
def ae(s, t, rel_eps=None, abs_eps=None):
|
149 |
+
return s.ctx.almosteq(s, t, rel_eps, abs_eps)
|
150 |
+
|
151 |
+
class ivmpc(object):
|
152 |
+
|
153 |
+
def __new__(cls, re=0, im=0):
|
154 |
+
re = cls.ctx.convert(re)
|
155 |
+
im = cls.ctx.convert(im)
|
156 |
+
y = new(cls)
|
157 |
+
y._mpci_ = re._mpi_, im._mpi_
|
158 |
+
return y
|
159 |
+
|
160 |
+
def __hash__(self):
|
161 |
+
(a, b), (c,d) = self._mpci_
|
162 |
+
if a == b and c == d:
|
163 |
+
return mpc_hash((a, c))
|
164 |
+
else:
|
165 |
+
return hash(self._mpci_)
|
166 |
+
|
167 |
+
def __repr__(s):
|
168 |
+
if s.ctx.pretty:
|
169 |
+
return str(s)
|
170 |
+
return "iv.mpc(%s, %s)" % (repr(s.real), repr(s.imag))
|
171 |
+
|
172 |
+
def __str__(s):
|
173 |
+
return "(%s + %s*j)" % (str(s.real), str(s.imag))
|
174 |
+
|
175 |
+
@property
|
176 |
+
def a(self):
|
177 |
+
(a, b), (c,d) = self._mpci_
|
178 |
+
return self.ctx.make_mpf((a, a))
|
179 |
+
|
180 |
+
@property
|
181 |
+
def b(self):
|
182 |
+
(a, b), (c,d) = self._mpci_
|
183 |
+
return self.ctx.make_mpf((b, b))
|
184 |
+
|
185 |
+
@property
|
186 |
+
def c(self):
|
187 |
+
(a, b), (c,d) = self._mpci_
|
188 |
+
return self.ctx.make_mpf((c, c))
|
189 |
+
|
190 |
+
@property
|
191 |
+
def d(self):
|
192 |
+
(a, b), (c,d) = self._mpci_
|
193 |
+
return self.ctx.make_mpf((d, d))
|
194 |
+
|
195 |
+
@property
|
196 |
+
def real(s):
|
197 |
+
return s.ctx.make_mpf(s._mpci_[0])
|
198 |
+
|
199 |
+
@property
|
200 |
+
def imag(s):
|
201 |
+
return s.ctx.make_mpf(s._mpci_[1])
|
202 |
+
|
203 |
+
def conjugate(s):
|
204 |
+
a, b = s._mpci_
|
205 |
+
return s.ctx.make_mpc((a, mpf_neg(b)))
|
206 |
+
|
207 |
+
def overlap(s, t):
|
208 |
+
t = s.ctx.convert(t)
|
209 |
+
real_overlap = (s.a <= t.a <= s.b) or (s.a <= t.b <= s.b) or (t.a <= s.a <= t.b) or (t.a <= s.b <= t.b)
|
210 |
+
imag_overlap = (s.c <= t.c <= s.d) or (s.c <= t.d <= s.d) or (t.c <= s.c <= t.d) or (t.c <= s.d <= t.d)
|
211 |
+
return real_overlap and imag_overlap
|
212 |
+
|
213 |
+
def __contains__(s, t):
|
214 |
+
t = s.ctx.convert(t)
|
215 |
+
return t.real in s.real and t.imag in s.imag
|
216 |
+
|
217 |
+
def _compare(s, t, ne=False):
|
218 |
+
if not isinstance(t, s.ctx._types):
|
219 |
+
try:
|
220 |
+
t = s.ctx.convert(t)
|
221 |
+
except:
|
222 |
+
return NotImplemented
|
223 |
+
if hasattr(t, '_mpi_'):
|
224 |
+
tval = t._mpi_, mpi_zero
|
225 |
+
elif hasattr(t, '_mpci_'):
|
226 |
+
tval = t._mpci_
|
227 |
+
if ne:
|
228 |
+
return s._mpci_ != tval
|
229 |
+
return s._mpci_ == tval
|
230 |
+
|
231 |
+
def __eq__(s, t): return s._compare(t)
|
232 |
+
def __ne__(s, t): return s._compare(t, True)
|
233 |
+
|
234 |
+
def __lt__(s, t): raise TypeError("complex intervals cannot be ordered")
|
235 |
+
__le__ = __gt__ = __ge__ = __lt__
|
236 |
+
|
237 |
+
def __neg__(s): return s.ctx.make_mpc(mpci_neg(s._mpci_, s.ctx.prec))
|
238 |
+
def __pos__(s): return s.ctx.make_mpc(mpci_pos(s._mpci_, s.ctx.prec))
|
239 |
+
def __abs__(s): return s.ctx.make_mpf(mpci_abs(s._mpci_, s.ctx.prec))
|
240 |
+
|
241 |
+
def ae(s, t, rel_eps=None, abs_eps=None):
|
242 |
+
return s.ctx.almosteq(s, t, rel_eps, abs_eps)
|
243 |
+
|
244 |
+
def _binary_op(f_real, f_complex):
|
245 |
+
def g_complex(ctx, sval, tval):
|
246 |
+
return ctx.make_mpc(f_complex(sval, tval, ctx.prec))
|
247 |
+
def g_real(ctx, sval, tval):
|
248 |
+
try:
|
249 |
+
return ctx.make_mpf(f_real(sval, tval, ctx.prec))
|
250 |
+
except ComplexResult:
|
251 |
+
sval = (sval, mpi_zero)
|
252 |
+
tval = (tval, mpi_zero)
|
253 |
+
return g_complex(ctx, sval, tval)
|
254 |
+
def lop_real(s, t):
|
255 |
+
if isinstance(t, _matrix): return NotImplemented
|
256 |
+
ctx = s.ctx
|
257 |
+
if not isinstance(t, ctx._types): t = ctx.convert(t)
|
258 |
+
if hasattr(t, "_mpi_"): return g_real(ctx, s._mpi_, t._mpi_)
|
259 |
+
if hasattr(t, "_mpci_"): return g_complex(ctx, (s._mpi_, mpi_zero), t._mpci_)
|
260 |
+
return NotImplemented
|
261 |
+
def rop_real(s, t):
|
262 |
+
ctx = s.ctx
|
263 |
+
if not isinstance(t, ctx._types): t = ctx.convert(t)
|
264 |
+
if hasattr(t, "_mpi_"): return g_real(ctx, t._mpi_, s._mpi_)
|
265 |
+
if hasattr(t, "_mpci_"): return g_complex(ctx, t._mpci_, (s._mpi_, mpi_zero))
|
266 |
+
return NotImplemented
|
267 |
+
def lop_complex(s, t):
|
268 |
+
if isinstance(t, _matrix): return NotImplemented
|
269 |
+
ctx = s.ctx
|
270 |
+
if not isinstance(t, s.ctx._types):
|
271 |
+
try:
|
272 |
+
t = s.ctx.convert(t)
|
273 |
+
except (ValueError, TypeError):
|
274 |
+
return NotImplemented
|
275 |
+
return g_complex(ctx, s._mpci_, t._mpci_)
|
276 |
+
def rop_complex(s, t):
|
277 |
+
ctx = s.ctx
|
278 |
+
if not isinstance(t, s.ctx._types):
|
279 |
+
t = s.ctx.convert(t)
|
280 |
+
return g_complex(ctx, t._mpci_, s._mpci_)
|
281 |
+
return lop_real, rop_real, lop_complex, rop_complex
|
282 |
+
|
283 |
+
ivmpf.__add__, ivmpf.__radd__, ivmpc.__add__, ivmpc.__radd__ = _binary_op(mpi_add, mpci_add)
|
284 |
+
ivmpf.__sub__, ivmpf.__rsub__, ivmpc.__sub__, ivmpc.__rsub__ = _binary_op(mpi_sub, mpci_sub)
|
285 |
+
ivmpf.__mul__, ivmpf.__rmul__, ivmpc.__mul__, ivmpc.__rmul__ = _binary_op(mpi_mul, mpci_mul)
|
286 |
+
ivmpf.__div__, ivmpf.__rdiv__, ivmpc.__div__, ivmpc.__rdiv__ = _binary_op(mpi_div, mpci_div)
|
287 |
+
ivmpf.__pow__, ivmpf.__rpow__, ivmpc.__pow__, ivmpc.__rpow__ = _binary_op(mpi_pow, mpci_pow)
|
288 |
+
|
289 |
+
ivmpf.__truediv__ = ivmpf.__div__; ivmpf.__rtruediv__ = ivmpf.__rdiv__
|
290 |
+
ivmpc.__truediv__ = ivmpc.__div__; ivmpc.__rtruediv__ = ivmpc.__rdiv__
|
291 |
+
|
292 |
+
class ivmpf_constant(ivmpf):
|
293 |
+
def __new__(cls, f):
|
294 |
+
self = new(cls)
|
295 |
+
self._f = f
|
296 |
+
return self
|
297 |
+
def _get_mpi_(self):
|
298 |
+
prec = self.ctx._prec[0]
|
299 |
+
a = self._f(prec, round_floor)
|
300 |
+
b = self._f(prec, round_ceiling)
|
301 |
+
return a, b
|
302 |
+
_mpi_ = property(_get_mpi_)
|
303 |
+
|
304 |
+
class MPIntervalContext(StandardBaseContext):
|
305 |
+
|
306 |
+
def __init__(ctx):
|
307 |
+
ctx.mpf = type('ivmpf', (ivmpf,), {})
|
308 |
+
ctx.mpc = type('ivmpc', (ivmpc,), {})
|
309 |
+
ctx._types = (ctx.mpf, ctx.mpc)
|
310 |
+
ctx._constant = type('ivmpf_constant', (ivmpf_constant,), {})
|
311 |
+
ctx._prec = [53]
|
312 |
+
ctx._set_prec(53)
|
313 |
+
ctx._constant._ctxdata = ctx.mpf._ctxdata = ctx.mpc._ctxdata = [ctx.mpf, new, ctx._prec]
|
314 |
+
ctx._constant.ctx = ctx.mpf.ctx = ctx.mpc.ctx = ctx
|
315 |
+
ctx.pretty = False
|
316 |
+
StandardBaseContext.__init__(ctx)
|
317 |
+
ctx._init_builtins()
|
318 |
+
|
319 |
+
def _mpi(ctx, a, b=None):
|
320 |
+
if b is None:
|
321 |
+
return ctx.mpf(a)
|
322 |
+
return ctx.mpf((a,b))
|
323 |
+
|
324 |
+
def _init_builtins(ctx):
|
325 |
+
ctx.one = ctx.mpf(1)
|
326 |
+
ctx.zero = ctx.mpf(0)
|
327 |
+
ctx.inf = ctx.mpf('inf')
|
328 |
+
ctx.ninf = -ctx.inf
|
329 |
+
ctx.nan = ctx.mpf('nan')
|
330 |
+
ctx.j = ctx.mpc(0,1)
|
331 |
+
ctx.exp = ctx._wrap_mpi_function(libmp.mpi_exp, libmp.mpci_exp)
|
332 |
+
ctx.sqrt = ctx._wrap_mpi_function(libmp.mpi_sqrt)
|
333 |
+
ctx.ln = ctx._wrap_mpi_function(libmp.mpi_log, libmp.mpci_log)
|
334 |
+
ctx.cos = ctx._wrap_mpi_function(libmp.mpi_cos, libmp.mpci_cos)
|
335 |
+
ctx.sin = ctx._wrap_mpi_function(libmp.mpi_sin, libmp.mpci_sin)
|
336 |
+
ctx.tan = ctx._wrap_mpi_function(libmp.mpi_tan)
|
337 |
+
ctx.gamma = ctx._wrap_mpi_function(libmp.mpi_gamma, libmp.mpci_gamma)
|
338 |
+
ctx.loggamma = ctx._wrap_mpi_function(libmp.mpi_loggamma, libmp.mpci_loggamma)
|
339 |
+
ctx.rgamma = ctx._wrap_mpi_function(libmp.mpi_rgamma, libmp.mpci_rgamma)
|
340 |
+
ctx.factorial = ctx._wrap_mpi_function(libmp.mpi_factorial, libmp.mpci_factorial)
|
341 |
+
ctx.fac = ctx.factorial
|
342 |
+
|
343 |
+
ctx.eps = ctx._constant(lambda prec, rnd: (0, MPZ_ONE, 1-prec, 1))
|
344 |
+
ctx.pi = ctx._constant(libmp.mpf_pi)
|
345 |
+
ctx.e = ctx._constant(libmp.mpf_e)
|
346 |
+
ctx.ln2 = ctx._constant(libmp.mpf_ln2)
|
347 |
+
ctx.ln10 = ctx._constant(libmp.mpf_ln10)
|
348 |
+
ctx.phi = ctx._constant(libmp.mpf_phi)
|
349 |
+
ctx.euler = ctx._constant(libmp.mpf_euler)
|
350 |
+
ctx.catalan = ctx._constant(libmp.mpf_catalan)
|
351 |
+
ctx.glaisher = ctx._constant(libmp.mpf_glaisher)
|
352 |
+
ctx.khinchin = ctx._constant(libmp.mpf_khinchin)
|
353 |
+
ctx.twinprime = ctx._constant(libmp.mpf_twinprime)
|
354 |
+
|
355 |
+
def _wrap_mpi_function(ctx, f_real, f_complex=None):
|
356 |
+
def g(x, **kwargs):
|
357 |
+
if kwargs:
|
358 |
+
prec = kwargs.get('prec', ctx._prec[0])
|
359 |
+
else:
|
360 |
+
prec = ctx._prec[0]
|
361 |
+
x = ctx.convert(x)
|
362 |
+
if hasattr(x, "_mpi_"):
|
363 |
+
return ctx.make_mpf(f_real(x._mpi_, prec))
|
364 |
+
if hasattr(x, "_mpci_"):
|
365 |
+
return ctx.make_mpc(f_complex(x._mpci_, prec))
|
366 |
+
raise ValueError
|
367 |
+
return g
|
368 |
+
|
369 |
+
@classmethod
|
370 |
+
def _wrap_specfun(cls, name, f, wrap):
|
371 |
+
if wrap:
|
372 |
+
def f_wrapped(ctx, *args, **kwargs):
|
373 |
+
convert = ctx.convert
|
374 |
+
args = [convert(a) for a in args]
|
375 |
+
prec = ctx.prec
|
376 |
+
try:
|
377 |
+
ctx.prec += 10
|
378 |
+
retval = f(ctx, *args, **kwargs)
|
379 |
+
finally:
|
380 |
+
ctx.prec = prec
|
381 |
+
return +retval
|
382 |
+
else:
|
383 |
+
f_wrapped = f
|
384 |
+
setattr(cls, name, f_wrapped)
|
385 |
+
|
386 |
+
def _set_prec(ctx, n):
|
387 |
+
ctx._prec[0] = max(1, int(n))
|
388 |
+
ctx._dps = prec_to_dps(n)
|
389 |
+
|
390 |
+
def _set_dps(ctx, n):
|
391 |
+
ctx._prec[0] = dps_to_prec(n)
|
392 |
+
ctx._dps = max(1, int(n))
|
393 |
+
|
394 |
+
prec = property(lambda ctx: ctx._prec[0], _set_prec)
|
395 |
+
dps = property(lambda ctx: ctx._dps, _set_dps)
|
396 |
+
|
397 |
+
def make_mpf(ctx, v):
|
398 |
+
a = new(ctx.mpf)
|
399 |
+
a._mpi_ = v
|
400 |
+
return a
|
401 |
+
|
402 |
+
def make_mpc(ctx, v):
|
403 |
+
a = new(ctx.mpc)
|
404 |
+
a._mpci_ = v
|
405 |
+
return a
|
406 |
+
|
407 |
+
def _mpq(ctx, pq):
|
408 |
+
p, q = pq
|
409 |
+
a = libmp.from_rational(p, q, ctx.prec, round_floor)
|
410 |
+
b = libmp.from_rational(p, q, ctx.prec, round_ceiling)
|
411 |
+
return ctx.make_mpf((a, b))
|
412 |
+
|
413 |
+
def convert(ctx, x):
|
414 |
+
if isinstance(x, (ctx.mpf, ctx.mpc)):
|
415 |
+
return x
|
416 |
+
if isinstance(x, ctx._constant):
|
417 |
+
return +x
|
418 |
+
if isinstance(x, complex) or hasattr(x, "_mpc_"):
|
419 |
+
re = ctx.convert(x.real)
|
420 |
+
im = ctx.convert(x.imag)
|
421 |
+
return ctx.mpc(re,im)
|
422 |
+
if isinstance(x, basestring):
|
423 |
+
v = mpi_from_str(x, ctx.prec)
|
424 |
+
return ctx.make_mpf(v)
|
425 |
+
if hasattr(x, "_mpi_"):
|
426 |
+
a, b = x._mpi_
|
427 |
+
else:
|
428 |
+
try:
|
429 |
+
a, b = x
|
430 |
+
except (TypeError, ValueError):
|
431 |
+
a = b = x
|
432 |
+
if hasattr(a, "_mpi_"):
|
433 |
+
a = a._mpi_[0]
|
434 |
+
else:
|
435 |
+
a = convert_mpf_(a, ctx.prec, round_floor)
|
436 |
+
if hasattr(b, "_mpi_"):
|
437 |
+
b = b._mpi_[1]
|
438 |
+
else:
|
439 |
+
b = convert_mpf_(b, ctx.prec, round_ceiling)
|
440 |
+
if a == fnan or b == fnan:
|
441 |
+
a = fninf
|
442 |
+
b = finf
|
443 |
+
assert mpf_le(a, b), "endpoints must be properly ordered"
|
444 |
+
return ctx.make_mpf((a, b))
|
445 |
+
|
446 |
+
def nstr(ctx, x, n=5, **kwargs):
|
447 |
+
x = ctx.convert(x)
|
448 |
+
if hasattr(x, "_mpi_"):
|
449 |
+
return libmp.mpi_to_str(x._mpi_, n, **kwargs)
|
450 |
+
if hasattr(x, "_mpci_"):
|
451 |
+
re = libmp.mpi_to_str(x._mpci_[0], n, **kwargs)
|
452 |
+
im = libmp.mpi_to_str(x._mpci_[1], n, **kwargs)
|
453 |
+
return "(%s + %s*j)" % (re, im)
|
454 |
+
|
455 |
+
def mag(ctx, x):
|
456 |
+
x = ctx.convert(x)
|
457 |
+
if isinstance(x, ctx.mpc):
|
458 |
+
return max(ctx.mag(x.real), ctx.mag(x.imag)) + 1
|
459 |
+
a, b = libmp.mpi_abs(x._mpi_)
|
460 |
+
sign, man, exp, bc = b
|
461 |
+
if man:
|
462 |
+
return exp+bc
|
463 |
+
if b == fzero:
|
464 |
+
return ctx.ninf
|
465 |
+
if b == fnan:
|
466 |
+
return ctx.nan
|
467 |
+
return ctx.inf
|
468 |
+
|
469 |
+
def isnan(ctx, x):
|
470 |
+
return False
|
471 |
+
|
472 |
+
def isinf(ctx, x):
|
473 |
+
return x == ctx.inf
|
474 |
+
|
475 |
+
def isint(ctx, x):
|
476 |
+
x = ctx.convert(x)
|
477 |
+
a, b = x._mpi_
|
478 |
+
if a == b:
|
479 |
+
sign, man, exp, bc = a
|
480 |
+
if man:
|
481 |
+
return exp >= 0
|
482 |
+
return a == fzero
|
483 |
+
return None
|
484 |
+
|
485 |
+
def ldexp(ctx, x, n):
|
486 |
+
a, b = ctx.convert(x)._mpi_
|
487 |
+
a = libmp.mpf_shift(a, n)
|
488 |
+
b = libmp.mpf_shift(b, n)
|
489 |
+
return ctx.make_mpf((a,b))
|
490 |
+
|
491 |
+
def absmin(ctx, x):
|
492 |
+
return abs(ctx.convert(x)).a
|
493 |
+
|
494 |
+
def absmax(ctx, x):
|
495 |
+
return abs(ctx.convert(x)).b
|
496 |
+
|
497 |
+
def atan2(ctx, y, x):
|
498 |
+
y = ctx.convert(y)._mpi_
|
499 |
+
x = ctx.convert(x)._mpi_
|
500 |
+
return ctx.make_mpf(libmp.mpi_atan2(y,x,ctx.prec))
|
501 |
+
|
502 |
+
def _convert_param(ctx, x):
|
503 |
+
if isinstance(x, libmp.int_types):
|
504 |
+
return x, 'Z'
|
505 |
+
if isinstance(x, tuple):
|
506 |
+
p, q = x
|
507 |
+
return (ctx.mpf(p) / ctx.mpf(q), 'R')
|
508 |
+
x = ctx.convert(x)
|
509 |
+
if isinstance(x, ctx.mpf):
|
510 |
+
return x, 'R'
|
511 |
+
if isinstance(x, ctx.mpc):
|
512 |
+
return x, 'C'
|
513 |
+
raise ValueError
|
514 |
+
|
515 |
+
def _is_real_type(ctx, z):
|
516 |
+
return isinstance(z, ctx.mpf) or isinstance(z, int_types)
|
517 |
+
|
518 |
+
def _is_complex_type(ctx, z):
|
519 |
+
return isinstance(z, ctx.mpc)
|
520 |
+
|
521 |
+
def hypsum(ctx, p, q, types, coeffs, z, maxterms=6000, **kwargs):
|
522 |
+
coeffs = list(coeffs)
|
523 |
+
num = range(p)
|
524 |
+
den = range(p,p+q)
|
525 |
+
#tol = ctx.eps
|
526 |
+
s = t = ctx.one
|
527 |
+
k = 0
|
528 |
+
while 1:
|
529 |
+
for i in num: t *= (coeffs[i]+k)
|
530 |
+
for i in den: t /= (coeffs[i]+k)
|
531 |
+
k += 1; t /= k; t *= z; s += t
|
532 |
+
if t == 0:
|
533 |
+
return s
|
534 |
+
#if abs(t) < tol:
|
535 |
+
# return s
|
536 |
+
if k > maxterms:
|
537 |
+
raise ctx.NoConvergence
|
538 |
+
|
539 |
+
|
540 |
+
# Register with "numbers" ABC
|
541 |
+
# We do not subclass, hence we do not use the @abstractmethod checks. While
|
542 |
+
# this is less invasive it may turn out that we do not actually support
|
543 |
+
# parts of the expected interfaces. See
|
544 |
+
# http://docs.python.org/2/library/numbers.html for list of abstract
|
545 |
+
# methods.
|
546 |
+
try:
|
547 |
+
import numbers
|
548 |
+
numbers.Complex.register(ivmpc)
|
549 |
+
numbers.Real.register(ivmpf)
|
550 |
+
except ImportError:
|
551 |
+
pass
|
env-llmeval/lib/python3.10/site-packages/mpmath/ctx_mp.py
ADDED
@@ -0,0 +1,1339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module defines the mpf, mpc classes, and standard functions for
|
3 |
+
operating with them.
|
4 |
+
"""
|
5 |
+
__docformat__ = 'plaintext'
|
6 |
+
|
7 |
+
import functools
|
8 |
+
|
9 |
+
import re
|
10 |
+
|
11 |
+
from .ctx_base import StandardBaseContext
|
12 |
+
|
13 |
+
from .libmp.backend import basestring, BACKEND
|
14 |
+
|
15 |
+
from . import libmp
|
16 |
+
|
17 |
+
from .libmp import (MPZ, MPZ_ZERO, MPZ_ONE, int_types, repr_dps,
|
18 |
+
round_floor, round_ceiling, dps_to_prec, round_nearest, prec_to_dps,
|
19 |
+
ComplexResult, to_pickable, from_pickable, normalize,
|
20 |
+
from_int, from_float, from_str, to_int, to_float, to_str,
|
21 |
+
from_rational, from_man_exp,
|
22 |
+
fone, fzero, finf, fninf, fnan,
|
23 |
+
mpf_abs, mpf_pos, mpf_neg, mpf_add, mpf_sub, mpf_mul, mpf_mul_int,
|
24 |
+
mpf_div, mpf_rdiv_int, mpf_pow_int, mpf_mod,
|
25 |
+
mpf_eq, mpf_cmp, mpf_lt, mpf_gt, mpf_le, mpf_ge,
|
26 |
+
mpf_hash, mpf_rand,
|
27 |
+
mpf_sum,
|
28 |
+
bitcount, to_fixed,
|
29 |
+
mpc_to_str,
|
30 |
+
mpc_to_complex, mpc_hash, mpc_pos, mpc_is_nonzero, mpc_neg, mpc_conjugate,
|
31 |
+
mpc_abs, mpc_add, mpc_add_mpf, mpc_sub, mpc_sub_mpf, mpc_mul, mpc_mul_mpf,
|
32 |
+
mpc_mul_int, mpc_div, mpc_div_mpf, mpc_pow, mpc_pow_mpf, mpc_pow_int,
|
33 |
+
mpc_mpf_div,
|
34 |
+
mpf_pow,
|
35 |
+
mpf_pi, mpf_degree, mpf_e, mpf_phi, mpf_ln2, mpf_ln10,
|
36 |
+
mpf_euler, mpf_catalan, mpf_apery, mpf_khinchin,
|
37 |
+
mpf_glaisher, mpf_twinprime, mpf_mertens,
|
38 |
+
int_types)
|
39 |
+
|
40 |
+
from . import function_docs
|
41 |
+
from . import rational
|
42 |
+
|
43 |
+
new = object.__new__
|
44 |
+
|
45 |
+
get_complex = re.compile(r'^\(?(?P<re>[\+\-]?\d*(\.\d*)?(e[\+\-]?\d+)?)??'
|
46 |
+
r'(?P<im>[\+\-]?\d*(\.\d*)?(e[\+\-]?\d+)?j)?\)?$')
|
47 |
+
|
48 |
+
if BACKEND == 'sage':
|
49 |
+
from sage.libs.mpmath.ext_main import Context as BaseMPContext
|
50 |
+
# pickle hack
|
51 |
+
import sage.libs.mpmath.ext_main as _mpf_module
|
52 |
+
else:
|
53 |
+
from .ctx_mp_python import PythonMPContext as BaseMPContext
|
54 |
+
from . import ctx_mp_python as _mpf_module
|
55 |
+
|
56 |
+
from .ctx_mp_python import _mpf, _mpc, mpnumeric
|
57 |
+
|
58 |
+
class MPContext(BaseMPContext, StandardBaseContext):
|
59 |
+
"""
|
60 |
+
Context for multiprecision arithmetic with a global precision.
|
61 |
+
"""
|
62 |
+
|
63 |
+
def __init__(ctx):
|
64 |
+
BaseMPContext.__init__(ctx)
|
65 |
+
ctx.trap_complex = False
|
66 |
+
ctx.pretty = False
|
67 |
+
ctx.types = [ctx.mpf, ctx.mpc, ctx.constant]
|
68 |
+
ctx._mpq = rational.mpq
|
69 |
+
ctx.default()
|
70 |
+
StandardBaseContext.__init__(ctx)
|
71 |
+
|
72 |
+
ctx.mpq = rational.mpq
|
73 |
+
ctx.init_builtins()
|
74 |
+
|
75 |
+
ctx.hyp_summators = {}
|
76 |
+
|
77 |
+
ctx._init_aliases()
|
78 |
+
|
79 |
+
# XXX: automate
|
80 |
+
try:
|
81 |
+
ctx.bernoulli.im_func.func_doc = function_docs.bernoulli
|
82 |
+
ctx.primepi.im_func.func_doc = function_docs.primepi
|
83 |
+
ctx.psi.im_func.func_doc = function_docs.psi
|
84 |
+
ctx.atan2.im_func.func_doc = function_docs.atan2
|
85 |
+
except AttributeError:
|
86 |
+
# python 3
|
87 |
+
ctx.bernoulli.__func__.func_doc = function_docs.bernoulli
|
88 |
+
ctx.primepi.__func__.func_doc = function_docs.primepi
|
89 |
+
ctx.psi.__func__.func_doc = function_docs.psi
|
90 |
+
ctx.atan2.__func__.func_doc = function_docs.atan2
|
91 |
+
|
92 |
+
ctx.digamma.func_doc = function_docs.digamma
|
93 |
+
ctx.cospi.func_doc = function_docs.cospi
|
94 |
+
ctx.sinpi.func_doc = function_docs.sinpi
|
95 |
+
|
96 |
+
def init_builtins(ctx):
|
97 |
+
|
98 |
+
mpf = ctx.mpf
|
99 |
+
mpc = ctx.mpc
|
100 |
+
|
101 |
+
# Exact constants
|
102 |
+
ctx.one = ctx.make_mpf(fone)
|
103 |
+
ctx.zero = ctx.make_mpf(fzero)
|
104 |
+
ctx.j = ctx.make_mpc((fzero,fone))
|
105 |
+
ctx.inf = ctx.make_mpf(finf)
|
106 |
+
ctx.ninf = ctx.make_mpf(fninf)
|
107 |
+
ctx.nan = ctx.make_mpf(fnan)
|
108 |
+
|
109 |
+
eps = ctx.constant(lambda prec, rnd: (0, MPZ_ONE, 1-prec, 1),
|
110 |
+
"epsilon of working precision", "eps")
|
111 |
+
ctx.eps = eps
|
112 |
+
|
113 |
+
# Approximate constants
|
114 |
+
ctx.pi = ctx.constant(mpf_pi, "pi", "pi")
|
115 |
+
ctx.ln2 = ctx.constant(mpf_ln2, "ln(2)", "ln2")
|
116 |
+
ctx.ln10 = ctx.constant(mpf_ln10, "ln(10)", "ln10")
|
117 |
+
ctx.phi = ctx.constant(mpf_phi, "Golden ratio phi", "phi")
|
118 |
+
ctx.e = ctx.constant(mpf_e, "e = exp(1)", "e")
|
119 |
+
ctx.euler = ctx.constant(mpf_euler, "Euler's constant", "euler")
|
120 |
+
ctx.catalan = ctx.constant(mpf_catalan, "Catalan's constant", "catalan")
|
121 |
+
ctx.khinchin = ctx.constant(mpf_khinchin, "Khinchin's constant", "khinchin")
|
122 |
+
ctx.glaisher = ctx.constant(mpf_glaisher, "Glaisher's constant", "glaisher")
|
123 |
+
ctx.apery = ctx.constant(mpf_apery, "Apery's constant", "apery")
|
124 |
+
ctx.degree = ctx.constant(mpf_degree, "1 deg = pi / 180", "degree")
|
125 |
+
ctx.twinprime = ctx.constant(mpf_twinprime, "Twin prime constant", "twinprime")
|
126 |
+
ctx.mertens = ctx.constant(mpf_mertens, "Mertens' constant", "mertens")
|
127 |
+
|
128 |
+
# Standard functions
|
129 |
+
ctx.sqrt = ctx._wrap_libmp_function(libmp.mpf_sqrt, libmp.mpc_sqrt)
|
130 |
+
ctx.cbrt = ctx._wrap_libmp_function(libmp.mpf_cbrt, libmp.mpc_cbrt)
|
131 |
+
ctx.ln = ctx._wrap_libmp_function(libmp.mpf_log, libmp.mpc_log)
|
132 |
+
ctx.atan = ctx._wrap_libmp_function(libmp.mpf_atan, libmp.mpc_atan)
|
133 |
+
ctx.exp = ctx._wrap_libmp_function(libmp.mpf_exp, libmp.mpc_exp)
|
134 |
+
ctx.expj = ctx._wrap_libmp_function(libmp.mpf_expj, libmp.mpc_expj)
|
135 |
+
ctx.expjpi = ctx._wrap_libmp_function(libmp.mpf_expjpi, libmp.mpc_expjpi)
|
136 |
+
ctx.sin = ctx._wrap_libmp_function(libmp.mpf_sin, libmp.mpc_sin)
|
137 |
+
ctx.cos = ctx._wrap_libmp_function(libmp.mpf_cos, libmp.mpc_cos)
|
138 |
+
ctx.tan = ctx._wrap_libmp_function(libmp.mpf_tan, libmp.mpc_tan)
|
139 |
+
ctx.sinh = ctx._wrap_libmp_function(libmp.mpf_sinh, libmp.mpc_sinh)
|
140 |
+
ctx.cosh = ctx._wrap_libmp_function(libmp.mpf_cosh, libmp.mpc_cosh)
|
141 |
+
ctx.tanh = ctx._wrap_libmp_function(libmp.mpf_tanh, libmp.mpc_tanh)
|
142 |
+
ctx.asin = ctx._wrap_libmp_function(libmp.mpf_asin, libmp.mpc_asin)
|
143 |
+
ctx.acos = ctx._wrap_libmp_function(libmp.mpf_acos, libmp.mpc_acos)
|
144 |
+
ctx.atan = ctx._wrap_libmp_function(libmp.mpf_atan, libmp.mpc_atan)
|
145 |
+
ctx.asinh = ctx._wrap_libmp_function(libmp.mpf_asinh, libmp.mpc_asinh)
|
146 |
+
ctx.acosh = ctx._wrap_libmp_function(libmp.mpf_acosh, libmp.mpc_acosh)
|
147 |
+
ctx.atanh = ctx._wrap_libmp_function(libmp.mpf_atanh, libmp.mpc_atanh)
|
148 |
+
ctx.sinpi = ctx._wrap_libmp_function(libmp.mpf_sin_pi, libmp.mpc_sin_pi)
|
149 |
+
ctx.cospi = ctx._wrap_libmp_function(libmp.mpf_cos_pi, libmp.mpc_cos_pi)
|
150 |
+
ctx.floor = ctx._wrap_libmp_function(libmp.mpf_floor, libmp.mpc_floor)
|
151 |
+
ctx.ceil = ctx._wrap_libmp_function(libmp.mpf_ceil, libmp.mpc_ceil)
|
152 |
+
ctx.nint = ctx._wrap_libmp_function(libmp.mpf_nint, libmp.mpc_nint)
|
153 |
+
ctx.frac = ctx._wrap_libmp_function(libmp.mpf_frac, libmp.mpc_frac)
|
154 |
+
ctx.fib = ctx.fibonacci = ctx._wrap_libmp_function(libmp.mpf_fibonacci, libmp.mpc_fibonacci)
|
155 |
+
|
156 |
+
ctx.gamma = ctx._wrap_libmp_function(libmp.mpf_gamma, libmp.mpc_gamma)
|
157 |
+
ctx.rgamma = ctx._wrap_libmp_function(libmp.mpf_rgamma, libmp.mpc_rgamma)
|
158 |
+
ctx.loggamma = ctx._wrap_libmp_function(libmp.mpf_loggamma, libmp.mpc_loggamma)
|
159 |
+
ctx.fac = ctx.factorial = ctx._wrap_libmp_function(libmp.mpf_factorial, libmp.mpc_factorial)
|
160 |
+
|
161 |
+
ctx.digamma = ctx._wrap_libmp_function(libmp.mpf_psi0, libmp.mpc_psi0)
|
162 |
+
ctx.harmonic = ctx._wrap_libmp_function(libmp.mpf_harmonic, libmp.mpc_harmonic)
|
163 |
+
ctx.ei = ctx._wrap_libmp_function(libmp.mpf_ei, libmp.mpc_ei)
|
164 |
+
ctx.e1 = ctx._wrap_libmp_function(libmp.mpf_e1, libmp.mpc_e1)
|
165 |
+
ctx._ci = ctx._wrap_libmp_function(libmp.mpf_ci, libmp.mpc_ci)
|
166 |
+
ctx._si = ctx._wrap_libmp_function(libmp.mpf_si, libmp.mpc_si)
|
167 |
+
ctx.ellipk = ctx._wrap_libmp_function(libmp.mpf_ellipk, libmp.mpc_ellipk)
|
168 |
+
ctx._ellipe = ctx._wrap_libmp_function(libmp.mpf_ellipe, libmp.mpc_ellipe)
|
169 |
+
ctx.agm1 = ctx._wrap_libmp_function(libmp.mpf_agm1, libmp.mpc_agm1)
|
170 |
+
ctx._erf = ctx._wrap_libmp_function(libmp.mpf_erf, None)
|
171 |
+
ctx._erfc = ctx._wrap_libmp_function(libmp.mpf_erfc, None)
|
172 |
+
ctx._zeta = ctx._wrap_libmp_function(libmp.mpf_zeta, libmp.mpc_zeta)
|
173 |
+
ctx._altzeta = ctx._wrap_libmp_function(libmp.mpf_altzeta, libmp.mpc_altzeta)
|
174 |
+
|
175 |
+
# Faster versions
|
176 |
+
ctx.sqrt = getattr(ctx, "_sage_sqrt", ctx.sqrt)
|
177 |
+
ctx.exp = getattr(ctx, "_sage_exp", ctx.exp)
|
178 |
+
ctx.ln = getattr(ctx, "_sage_ln", ctx.ln)
|
179 |
+
ctx.cos = getattr(ctx, "_sage_cos", ctx.cos)
|
180 |
+
ctx.sin = getattr(ctx, "_sage_sin", ctx.sin)
|
181 |
+
|
182 |
+
def to_fixed(ctx, x, prec):
|
183 |
+
return x.to_fixed(prec)
|
184 |
+
|
185 |
+
def hypot(ctx, x, y):
|
186 |
+
r"""
|
187 |
+
Computes the Euclidean norm of the vector `(x, y)`, equal
|
188 |
+
to `\sqrt{x^2 + y^2}`. Both `x` and `y` must be real."""
|
189 |
+
x = ctx.convert(x)
|
190 |
+
y = ctx.convert(y)
|
191 |
+
return ctx.make_mpf(libmp.mpf_hypot(x._mpf_, y._mpf_, *ctx._prec_rounding))
|
192 |
+
|
193 |
+
def _gamma_upper_int(ctx, n, z):
|
194 |
+
n = int(ctx._re(n))
|
195 |
+
if n == 0:
|
196 |
+
return ctx.e1(z)
|
197 |
+
if not hasattr(z, '_mpf_'):
|
198 |
+
raise NotImplementedError
|
199 |
+
prec, rounding = ctx._prec_rounding
|
200 |
+
real, imag = libmp.mpf_expint(n, z._mpf_, prec, rounding, gamma=True)
|
201 |
+
if imag is None:
|
202 |
+
return ctx.make_mpf(real)
|
203 |
+
else:
|
204 |
+
return ctx.make_mpc((real, imag))
|
205 |
+
|
206 |
+
def _expint_int(ctx, n, z):
|
207 |
+
n = int(n)
|
208 |
+
if n == 1:
|
209 |
+
return ctx.e1(z)
|
210 |
+
if not hasattr(z, '_mpf_'):
|
211 |
+
raise NotImplementedError
|
212 |
+
prec, rounding = ctx._prec_rounding
|
213 |
+
real, imag = libmp.mpf_expint(n, z._mpf_, prec, rounding)
|
214 |
+
if imag is None:
|
215 |
+
return ctx.make_mpf(real)
|
216 |
+
else:
|
217 |
+
return ctx.make_mpc((real, imag))
|
218 |
+
|
219 |
+
def _nthroot(ctx, x, n):
|
220 |
+
if hasattr(x, '_mpf_'):
|
221 |
+
try:
|
222 |
+
return ctx.make_mpf(libmp.mpf_nthroot(x._mpf_, n, *ctx._prec_rounding))
|
223 |
+
except ComplexResult:
|
224 |
+
if ctx.trap_complex:
|
225 |
+
raise
|
226 |
+
x = (x._mpf_, libmp.fzero)
|
227 |
+
else:
|
228 |
+
x = x._mpc_
|
229 |
+
return ctx.make_mpc(libmp.mpc_nthroot(x, n, *ctx._prec_rounding))
|
230 |
+
|
231 |
+
def _besselj(ctx, n, z):
|
232 |
+
prec, rounding = ctx._prec_rounding
|
233 |
+
if hasattr(z, '_mpf_'):
|
234 |
+
return ctx.make_mpf(libmp.mpf_besseljn(n, z._mpf_, prec, rounding))
|
235 |
+
elif hasattr(z, '_mpc_'):
|
236 |
+
return ctx.make_mpc(libmp.mpc_besseljn(n, z._mpc_, prec, rounding))
|
237 |
+
|
238 |
+
def _agm(ctx, a, b=1):
|
239 |
+
prec, rounding = ctx._prec_rounding
|
240 |
+
if hasattr(a, '_mpf_') and hasattr(b, '_mpf_'):
|
241 |
+
try:
|
242 |
+
v = libmp.mpf_agm(a._mpf_, b._mpf_, prec, rounding)
|
243 |
+
return ctx.make_mpf(v)
|
244 |
+
except ComplexResult:
|
245 |
+
pass
|
246 |
+
if hasattr(a, '_mpf_'): a = (a._mpf_, libmp.fzero)
|
247 |
+
else: a = a._mpc_
|
248 |
+
if hasattr(b, '_mpf_'): b = (b._mpf_, libmp.fzero)
|
249 |
+
else: b = b._mpc_
|
250 |
+
return ctx.make_mpc(libmp.mpc_agm(a, b, prec, rounding))
|
251 |
+
|
252 |
+
def bernoulli(ctx, n):
|
253 |
+
return ctx.make_mpf(libmp.mpf_bernoulli(int(n), *ctx._prec_rounding))
|
254 |
+
|
255 |
+
def _zeta_int(ctx, n):
|
256 |
+
return ctx.make_mpf(libmp.mpf_zeta_int(int(n), *ctx._prec_rounding))
|
257 |
+
|
258 |
+
def atan2(ctx, y, x):
|
259 |
+
x = ctx.convert(x)
|
260 |
+
y = ctx.convert(y)
|
261 |
+
return ctx.make_mpf(libmp.mpf_atan2(y._mpf_, x._mpf_, *ctx._prec_rounding))
|
262 |
+
|
263 |
+
def psi(ctx, m, z):
|
264 |
+
z = ctx.convert(z)
|
265 |
+
m = int(m)
|
266 |
+
if ctx._is_real_type(z):
|
267 |
+
return ctx.make_mpf(libmp.mpf_psi(m, z._mpf_, *ctx._prec_rounding))
|
268 |
+
else:
|
269 |
+
return ctx.make_mpc(libmp.mpc_psi(m, z._mpc_, *ctx._prec_rounding))
|
270 |
+
|
271 |
+
def cos_sin(ctx, x, **kwargs):
|
272 |
+
if type(x) not in ctx.types:
|
273 |
+
x = ctx.convert(x)
|
274 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
275 |
+
if hasattr(x, '_mpf_'):
|
276 |
+
c, s = libmp.mpf_cos_sin(x._mpf_, prec, rounding)
|
277 |
+
return ctx.make_mpf(c), ctx.make_mpf(s)
|
278 |
+
elif hasattr(x, '_mpc_'):
|
279 |
+
c, s = libmp.mpc_cos_sin(x._mpc_, prec, rounding)
|
280 |
+
return ctx.make_mpc(c), ctx.make_mpc(s)
|
281 |
+
else:
|
282 |
+
return ctx.cos(x, **kwargs), ctx.sin(x, **kwargs)
|
283 |
+
|
284 |
+
def cospi_sinpi(ctx, x, **kwargs):
|
285 |
+
if type(x) not in ctx.types:
|
286 |
+
x = ctx.convert(x)
|
287 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
288 |
+
if hasattr(x, '_mpf_'):
|
289 |
+
c, s = libmp.mpf_cos_sin_pi(x._mpf_, prec, rounding)
|
290 |
+
return ctx.make_mpf(c), ctx.make_mpf(s)
|
291 |
+
elif hasattr(x, '_mpc_'):
|
292 |
+
c, s = libmp.mpc_cos_sin_pi(x._mpc_, prec, rounding)
|
293 |
+
return ctx.make_mpc(c), ctx.make_mpc(s)
|
294 |
+
else:
|
295 |
+
return ctx.cos(x, **kwargs), ctx.sin(x, **kwargs)
|
296 |
+
|
297 |
+
def clone(ctx):
|
298 |
+
"""
|
299 |
+
Create a copy of the context, with the same working precision.
|
300 |
+
"""
|
301 |
+
a = ctx.__class__()
|
302 |
+
a.prec = ctx.prec
|
303 |
+
return a
|
304 |
+
|
305 |
+
# Several helper methods
|
306 |
+
# TODO: add more of these, make consistent, write docstrings, ...
|
307 |
+
|
308 |
+
def _is_real_type(ctx, x):
|
309 |
+
if hasattr(x, '_mpc_') or type(x) is complex:
|
310 |
+
return False
|
311 |
+
return True
|
312 |
+
|
313 |
+
def _is_complex_type(ctx, x):
|
314 |
+
if hasattr(x, '_mpc_') or type(x) is complex:
|
315 |
+
return True
|
316 |
+
return False
|
317 |
+
|
318 |
+
def isnan(ctx, x):
|
319 |
+
"""
|
320 |
+
Return *True* if *x* is a NaN (not-a-number), or for a complex
|
321 |
+
number, whether either the real or complex part is NaN;
|
322 |
+
otherwise return *False*::
|
323 |
+
|
324 |
+
>>> from mpmath import *
|
325 |
+
>>> isnan(3.14)
|
326 |
+
False
|
327 |
+
>>> isnan(nan)
|
328 |
+
True
|
329 |
+
>>> isnan(mpc(3.14,2.72))
|
330 |
+
False
|
331 |
+
>>> isnan(mpc(3.14,nan))
|
332 |
+
True
|
333 |
+
|
334 |
+
"""
|
335 |
+
if hasattr(x, "_mpf_"):
|
336 |
+
return x._mpf_ == fnan
|
337 |
+
if hasattr(x, "_mpc_"):
|
338 |
+
return fnan in x._mpc_
|
339 |
+
if isinstance(x, int_types) or isinstance(x, rational.mpq):
|
340 |
+
return False
|
341 |
+
x = ctx.convert(x)
|
342 |
+
if hasattr(x, '_mpf_') or hasattr(x, '_mpc_'):
|
343 |
+
return ctx.isnan(x)
|
344 |
+
raise TypeError("isnan() needs a number as input")
|
345 |
+
|
346 |
+
def isfinite(ctx, x):
|
347 |
+
"""
|
348 |
+
Return *True* if *x* is a finite number, i.e. neither
|
349 |
+
an infinity or a NaN.
|
350 |
+
|
351 |
+
>>> from mpmath import *
|
352 |
+
>>> isfinite(inf)
|
353 |
+
False
|
354 |
+
>>> isfinite(-inf)
|
355 |
+
False
|
356 |
+
>>> isfinite(3)
|
357 |
+
True
|
358 |
+
>>> isfinite(nan)
|
359 |
+
False
|
360 |
+
>>> isfinite(3+4j)
|
361 |
+
True
|
362 |
+
>>> isfinite(mpc(3,inf))
|
363 |
+
False
|
364 |
+
>>> isfinite(mpc(nan,3))
|
365 |
+
False
|
366 |
+
|
367 |
+
"""
|
368 |
+
if ctx.isinf(x) or ctx.isnan(x):
|
369 |
+
return False
|
370 |
+
return True
|
371 |
+
|
372 |
+
def isnpint(ctx, x):
|
373 |
+
"""
|
374 |
+
Determine if *x* is a nonpositive integer.
|
375 |
+
"""
|
376 |
+
if not x:
|
377 |
+
return True
|
378 |
+
if hasattr(x, '_mpf_'):
|
379 |
+
sign, man, exp, bc = x._mpf_
|
380 |
+
return sign and exp >= 0
|
381 |
+
if hasattr(x, '_mpc_'):
|
382 |
+
return not x.imag and ctx.isnpint(x.real)
|
383 |
+
if type(x) in int_types:
|
384 |
+
return x <= 0
|
385 |
+
if isinstance(x, ctx.mpq):
|
386 |
+
p, q = x._mpq_
|
387 |
+
if not p:
|
388 |
+
return True
|
389 |
+
return q == 1 and p <= 0
|
390 |
+
return ctx.isnpint(ctx.convert(x))
|
391 |
+
|
392 |
+
def __str__(ctx):
|
393 |
+
lines = ["Mpmath settings:",
|
394 |
+
(" mp.prec = %s" % ctx.prec).ljust(30) + "[default: 53]",
|
395 |
+
(" mp.dps = %s" % ctx.dps).ljust(30) + "[default: 15]",
|
396 |
+
(" mp.trap_complex = %s" % ctx.trap_complex).ljust(30) + "[default: False]",
|
397 |
+
]
|
398 |
+
return "\n".join(lines)
|
399 |
+
|
400 |
+
@property
|
401 |
+
def _repr_digits(ctx):
|
402 |
+
return repr_dps(ctx._prec)
|
403 |
+
|
404 |
+
@property
|
405 |
+
def _str_digits(ctx):
|
406 |
+
return ctx._dps
|
407 |
+
|
408 |
+
def extraprec(ctx, n, normalize_output=False):
|
409 |
+
"""
|
410 |
+
The block
|
411 |
+
|
412 |
+
with extraprec(n):
|
413 |
+
<code>
|
414 |
+
|
415 |
+
increases the precision n bits, executes <code>, and then
|
416 |
+
restores the precision.
|
417 |
+
|
418 |
+
extraprec(n)(f) returns a decorated version of the function f
|
419 |
+
that increases the working precision by n bits before execution,
|
420 |
+
and restores the parent precision afterwards. With
|
421 |
+
normalize_output=True, it rounds the return value to the parent
|
422 |
+
precision.
|
423 |
+
"""
|
424 |
+
return PrecisionManager(ctx, lambda p: p + n, None, normalize_output)
|
425 |
+
|
426 |
+
def extradps(ctx, n, normalize_output=False):
|
427 |
+
"""
|
428 |
+
This function is analogous to extraprec (see documentation)
|
429 |
+
but changes the decimal precision instead of the number of bits.
|
430 |
+
"""
|
431 |
+
return PrecisionManager(ctx, None, lambda d: d + n, normalize_output)
|
432 |
+
|
433 |
+
def workprec(ctx, n, normalize_output=False):
|
434 |
+
"""
|
435 |
+
The block
|
436 |
+
|
437 |
+
with workprec(n):
|
438 |
+
<code>
|
439 |
+
|
440 |
+
sets the precision to n bits, executes <code>, and then restores
|
441 |
+
the precision.
|
442 |
+
|
443 |
+
workprec(n)(f) returns a decorated version of the function f
|
444 |
+
that sets the precision to n bits before execution,
|
445 |
+
and restores the precision afterwards. With normalize_output=True,
|
446 |
+
it rounds the return value to the parent precision.
|
447 |
+
"""
|
448 |
+
return PrecisionManager(ctx, lambda p: n, None, normalize_output)
|
449 |
+
|
450 |
+
def workdps(ctx, n, normalize_output=False):
|
451 |
+
"""
|
452 |
+
This function is analogous to workprec (see documentation)
|
453 |
+
but changes the decimal precision instead of the number of bits.
|
454 |
+
"""
|
455 |
+
return PrecisionManager(ctx, None, lambda d: n, normalize_output)
|
456 |
+
|
457 |
+
def autoprec(ctx, f, maxprec=None, catch=(), verbose=False):
|
458 |
+
r"""
|
459 |
+
Return a wrapped copy of *f* that repeatedly evaluates *f*
|
460 |
+
with increasing precision until the result converges to the
|
461 |
+
full precision used at the point of the call.
|
462 |
+
|
463 |
+
This heuristically protects against rounding errors, at the cost of
|
464 |
+
roughly a 2x slowdown compared to manually setting the optimal
|
465 |
+
precision. This method can, however, easily be fooled if the results
|
466 |
+
from *f* depend "discontinuously" on the precision, for instance
|
467 |
+
if catastrophic cancellation can occur. Therefore, :func:`~mpmath.autoprec`
|
468 |
+
should be used judiciously.
|
469 |
+
|
470 |
+
**Examples**
|
471 |
+
|
472 |
+
Many functions are sensitive to perturbations of the input arguments.
|
473 |
+
If the arguments are decimal numbers, they may have to be converted
|
474 |
+
to binary at a much higher precision. If the amount of required
|
475 |
+
extra precision is unknown, :func:`~mpmath.autoprec` is convenient::
|
476 |
+
|
477 |
+
>>> from mpmath import *
|
478 |
+
>>> mp.dps = 15
|
479 |
+
>>> mp.pretty = True
|
480 |
+
>>> besselj(5, 125 * 10**28) # Exact input
|
481 |
+
-8.03284785591801e-17
|
482 |
+
>>> besselj(5, '1.25e30') # Bad
|
483 |
+
7.12954868316652e-16
|
484 |
+
>>> autoprec(besselj)(5, '1.25e30') # Good
|
485 |
+
-8.03284785591801e-17
|
486 |
+
|
487 |
+
The following fails to converge because `\sin(\pi) = 0` whereas all
|
488 |
+
finite-precision approximations of `\pi` give nonzero values::
|
489 |
+
|
490 |
+
>>> autoprec(sin)(pi) # doctest: +IGNORE_EXCEPTION_DETAIL
|
491 |
+
Traceback (most recent call last):
|
492 |
+
...
|
493 |
+
NoConvergence: autoprec: prec increased to 2910 without convergence
|
494 |
+
|
495 |
+
As the following example shows, :func:`~mpmath.autoprec` can protect against
|
496 |
+
cancellation, but is fooled by too severe cancellation::
|
497 |
+
|
498 |
+
>>> x = 1e-10
|
499 |
+
>>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x)
|
500 |
+
1.00000008274037e-10
|
501 |
+
1.00000000005e-10
|
502 |
+
1.00000000005e-10
|
503 |
+
>>> x = 1e-50
|
504 |
+
>>> exp(x)-1; expm1(x); autoprec(lambda t: exp(t)-1)(x)
|
505 |
+
0.0
|
506 |
+
1.0e-50
|
507 |
+
0.0
|
508 |
+
|
509 |
+
With *catch*, an exception or list of exceptions to intercept
|
510 |
+
may be specified. The raised exception is interpreted
|
511 |
+
as signaling insufficient precision. This permits, for example,
|
512 |
+
evaluating a function where a too low precision results in a
|
513 |
+
division by zero::
|
514 |
+
|
515 |
+
>>> f = lambda x: 1/(exp(x)-1)
|
516 |
+
>>> f(1e-30)
|
517 |
+
Traceback (most recent call last):
|
518 |
+
...
|
519 |
+
ZeroDivisionError
|
520 |
+
>>> autoprec(f, catch=ZeroDivisionError)(1e-30)
|
521 |
+
1.0e+30
|
522 |
+
|
523 |
+
|
524 |
+
"""
|
525 |
+
def f_autoprec_wrapped(*args, **kwargs):
|
526 |
+
prec = ctx.prec
|
527 |
+
if maxprec is None:
|
528 |
+
maxprec2 = ctx._default_hyper_maxprec(prec)
|
529 |
+
else:
|
530 |
+
maxprec2 = maxprec
|
531 |
+
try:
|
532 |
+
ctx.prec = prec + 10
|
533 |
+
try:
|
534 |
+
v1 = f(*args, **kwargs)
|
535 |
+
except catch:
|
536 |
+
v1 = ctx.nan
|
537 |
+
prec2 = prec + 20
|
538 |
+
while 1:
|
539 |
+
ctx.prec = prec2
|
540 |
+
try:
|
541 |
+
v2 = f(*args, **kwargs)
|
542 |
+
except catch:
|
543 |
+
v2 = ctx.nan
|
544 |
+
if v1 == v2:
|
545 |
+
break
|
546 |
+
err = ctx.mag(v2-v1) - ctx.mag(v2)
|
547 |
+
if err < (-prec):
|
548 |
+
break
|
549 |
+
if verbose:
|
550 |
+
print("autoprec: target=%s, prec=%s, accuracy=%s" \
|
551 |
+
% (prec, prec2, -err))
|
552 |
+
v1 = v2
|
553 |
+
if prec2 >= maxprec2:
|
554 |
+
raise ctx.NoConvergence(\
|
555 |
+
"autoprec: prec increased to %i without convergence"\
|
556 |
+
% prec2)
|
557 |
+
prec2 += int(prec2*2)
|
558 |
+
prec2 = min(prec2, maxprec2)
|
559 |
+
finally:
|
560 |
+
ctx.prec = prec
|
561 |
+
return +v2
|
562 |
+
return f_autoprec_wrapped
|
563 |
+
|
564 |
+
def nstr(ctx, x, n=6, **kwargs):
|
565 |
+
"""
|
566 |
+
Convert an ``mpf`` or ``mpc`` to a decimal string literal with *n*
|
567 |
+
significant digits. The small default value for *n* is chosen to
|
568 |
+
make this function useful for printing collections of numbers
|
569 |
+
(lists, matrices, etc).
|
570 |
+
|
571 |
+
If *x* is a list or tuple, :func:`~mpmath.nstr` is applied recursively
|
572 |
+
to each element. For unrecognized classes, :func:`~mpmath.nstr`
|
573 |
+
simply returns ``str(x)``.
|
574 |
+
|
575 |
+
The companion function :func:`~mpmath.nprint` prints the result
|
576 |
+
instead of returning it.
|
577 |
+
|
578 |
+
The keyword arguments *strip_zeros*, *min_fixed*, *max_fixed*
|
579 |
+
and *show_zero_exponent* are forwarded to :func:`~mpmath.libmp.to_str`.
|
580 |
+
|
581 |
+
The number will be printed in fixed-point format if the position
|
582 |
+
of the leading digit is strictly between min_fixed
|
583 |
+
(default = min(-dps/3,-5)) and max_fixed (default = dps).
|
584 |
+
|
585 |
+
To force fixed-point format always, set min_fixed = -inf,
|
586 |
+
max_fixed = +inf. To force floating-point format, set
|
587 |
+
min_fixed >= max_fixed.
|
588 |
+
|
589 |
+
>>> from mpmath import *
|
590 |
+
>>> nstr([+pi, ldexp(1,-500)])
|
591 |
+
'[3.14159, 3.05494e-151]'
|
592 |
+
>>> nprint([+pi, ldexp(1,-500)])
|
593 |
+
[3.14159, 3.05494e-151]
|
594 |
+
>>> nstr(mpf("5e-10"), 5)
|
595 |
+
'5.0e-10'
|
596 |
+
>>> nstr(mpf("5e-10"), 5, strip_zeros=False)
|
597 |
+
'5.0000e-10'
|
598 |
+
>>> nstr(mpf("5e-10"), 5, strip_zeros=False, min_fixed=-11)
|
599 |
+
'0.00000000050000'
|
600 |
+
>>> nstr(mpf(0), 5, show_zero_exponent=True)
|
601 |
+
'0.0e+0'
|
602 |
+
|
603 |
+
"""
|
604 |
+
if isinstance(x, list):
|
605 |
+
return "[%s]" % (", ".join(ctx.nstr(c, n, **kwargs) for c in x))
|
606 |
+
if isinstance(x, tuple):
|
607 |
+
return "(%s)" % (", ".join(ctx.nstr(c, n, **kwargs) for c in x))
|
608 |
+
if hasattr(x, '_mpf_'):
|
609 |
+
return to_str(x._mpf_, n, **kwargs)
|
610 |
+
if hasattr(x, '_mpc_'):
|
611 |
+
return "(" + mpc_to_str(x._mpc_, n, **kwargs) + ")"
|
612 |
+
if isinstance(x, basestring):
|
613 |
+
return repr(x)
|
614 |
+
if isinstance(x, ctx.matrix):
|
615 |
+
return x.__nstr__(n, **kwargs)
|
616 |
+
return str(x)
|
617 |
+
|
618 |
+
def _convert_fallback(ctx, x, strings):
|
619 |
+
if strings and isinstance(x, basestring):
|
620 |
+
if 'j' in x.lower():
|
621 |
+
x = x.lower().replace(' ', '')
|
622 |
+
match = get_complex.match(x)
|
623 |
+
re = match.group('re')
|
624 |
+
if not re:
|
625 |
+
re = 0
|
626 |
+
im = match.group('im').rstrip('j')
|
627 |
+
return ctx.mpc(ctx.convert(re), ctx.convert(im))
|
628 |
+
if hasattr(x, "_mpi_"):
|
629 |
+
a, b = x._mpi_
|
630 |
+
if a == b:
|
631 |
+
return ctx.make_mpf(a)
|
632 |
+
else:
|
633 |
+
raise ValueError("can only create mpf from zero-width interval")
|
634 |
+
raise TypeError("cannot create mpf from " + repr(x))
|
635 |
+
|
636 |
+
def mpmathify(ctx, *args, **kwargs):
|
637 |
+
return ctx.convert(*args, **kwargs)
|
638 |
+
|
639 |
+
def _parse_prec(ctx, kwargs):
|
640 |
+
if kwargs:
|
641 |
+
if kwargs.get('exact'):
|
642 |
+
return 0, 'f'
|
643 |
+
prec, rounding = ctx._prec_rounding
|
644 |
+
if 'rounding' in kwargs:
|
645 |
+
rounding = kwargs['rounding']
|
646 |
+
if 'prec' in kwargs:
|
647 |
+
prec = kwargs['prec']
|
648 |
+
if prec == ctx.inf:
|
649 |
+
return 0, 'f'
|
650 |
+
else:
|
651 |
+
prec = int(prec)
|
652 |
+
elif 'dps' in kwargs:
|
653 |
+
dps = kwargs['dps']
|
654 |
+
if dps == ctx.inf:
|
655 |
+
return 0, 'f'
|
656 |
+
prec = dps_to_prec(dps)
|
657 |
+
return prec, rounding
|
658 |
+
return ctx._prec_rounding
|
659 |
+
|
660 |
+
_exact_overflow_msg = "the exact result does not fit in memory"
|
661 |
+
|
662 |
+
_hypsum_msg = """hypsum() failed to converge to the requested %i bits of accuracy
|
663 |
+
using a working precision of %i bits. Try with a higher maxprec,
|
664 |
+
maxterms, or set zeroprec."""
|
665 |
+
|
666 |
+
def hypsum(ctx, p, q, flags, coeffs, z, accurate_small=True, **kwargs):
|
667 |
+
if hasattr(z, "_mpf_"):
|
668 |
+
key = p, q, flags, 'R'
|
669 |
+
v = z._mpf_
|
670 |
+
elif hasattr(z, "_mpc_"):
|
671 |
+
key = p, q, flags, 'C'
|
672 |
+
v = z._mpc_
|
673 |
+
if key not in ctx.hyp_summators:
|
674 |
+
ctx.hyp_summators[key] = libmp.make_hyp_summator(key)[1]
|
675 |
+
summator = ctx.hyp_summators[key]
|
676 |
+
prec = ctx.prec
|
677 |
+
maxprec = kwargs.get('maxprec', ctx._default_hyper_maxprec(prec))
|
678 |
+
extraprec = 50
|
679 |
+
epsshift = 25
|
680 |
+
# Jumps in magnitude occur when parameters are close to negative
|
681 |
+
# integers. We must ensure that these terms are included in
|
682 |
+
# the sum and added accurately
|
683 |
+
magnitude_check = {}
|
684 |
+
max_total_jump = 0
|
685 |
+
for i, c in enumerate(coeffs):
|
686 |
+
if flags[i] == 'Z':
|
687 |
+
if i >= p and c <= 0:
|
688 |
+
ok = False
|
689 |
+
for ii, cc in enumerate(coeffs[:p]):
|
690 |
+
# Note: c <= cc or c < cc, depending on convention
|
691 |
+
if flags[ii] == 'Z' and cc <= 0 and c <= cc:
|
692 |
+
ok = True
|
693 |
+
if not ok:
|
694 |
+
raise ZeroDivisionError("pole in hypergeometric series")
|
695 |
+
continue
|
696 |
+
n, d = ctx.nint_distance(c)
|
697 |
+
n = -int(n)
|
698 |
+
d = -d
|
699 |
+
if i >= p and n >= 0 and d > 4:
|
700 |
+
if n in magnitude_check:
|
701 |
+
magnitude_check[n] += d
|
702 |
+
else:
|
703 |
+
magnitude_check[n] = d
|
704 |
+
extraprec = max(extraprec, d - prec + 60)
|
705 |
+
max_total_jump += abs(d)
|
706 |
+
while 1:
|
707 |
+
if extraprec > maxprec:
|
708 |
+
raise ValueError(ctx._hypsum_msg % (prec, prec+extraprec))
|
709 |
+
wp = prec + extraprec
|
710 |
+
if magnitude_check:
|
711 |
+
mag_dict = dict((n,None) for n in magnitude_check)
|
712 |
+
else:
|
713 |
+
mag_dict = {}
|
714 |
+
zv, have_complex, magnitude = summator(coeffs, v, prec, wp, \
|
715 |
+
epsshift, mag_dict, **kwargs)
|
716 |
+
cancel = -magnitude
|
717 |
+
jumps_resolved = True
|
718 |
+
if extraprec < max_total_jump:
|
719 |
+
for n in mag_dict.values():
|
720 |
+
if (n is None) or (n < prec):
|
721 |
+
jumps_resolved = False
|
722 |
+
break
|
723 |
+
accurate = (cancel < extraprec-25-5 or not accurate_small)
|
724 |
+
if jumps_resolved:
|
725 |
+
if accurate:
|
726 |
+
break
|
727 |
+
# zero?
|
728 |
+
zeroprec = kwargs.get('zeroprec')
|
729 |
+
if zeroprec is not None:
|
730 |
+
if cancel > zeroprec:
|
731 |
+
if have_complex:
|
732 |
+
return ctx.mpc(0)
|
733 |
+
else:
|
734 |
+
return ctx.zero
|
735 |
+
|
736 |
+
# Some near-singularities were not included, so increase
|
737 |
+
# precision and repeat until they are
|
738 |
+
extraprec *= 2
|
739 |
+
# Possible workaround for bad roundoff in fixed-point arithmetic
|
740 |
+
epsshift += 5
|
741 |
+
extraprec += 5
|
742 |
+
|
743 |
+
if type(zv) is tuple:
|
744 |
+
if have_complex:
|
745 |
+
return ctx.make_mpc(zv)
|
746 |
+
else:
|
747 |
+
return ctx.make_mpf(zv)
|
748 |
+
else:
|
749 |
+
return zv
|
750 |
+
|
751 |
+
def ldexp(ctx, x, n):
|
752 |
+
r"""
|
753 |
+
Computes `x 2^n` efficiently. No rounding is performed.
|
754 |
+
The argument `x` must be a real floating-point number (or
|
755 |
+
possible to convert into one) and `n` must be a Python ``int``.
|
756 |
+
|
757 |
+
>>> from mpmath import *
|
758 |
+
>>> mp.dps = 15; mp.pretty = False
|
759 |
+
>>> ldexp(1, 10)
|
760 |
+
mpf('1024.0')
|
761 |
+
>>> ldexp(1, -3)
|
762 |
+
mpf('0.125')
|
763 |
+
|
764 |
+
"""
|
765 |
+
x = ctx.convert(x)
|
766 |
+
return ctx.make_mpf(libmp.mpf_shift(x._mpf_, n))
|
767 |
+
|
768 |
+
def frexp(ctx, x):
|
769 |
+
r"""
|
770 |
+
Given a real number `x`, returns `(y, n)` with `y \in [0.5, 1)`,
|
771 |
+
`n` a Python integer, and such that `x = y 2^n`. No rounding is
|
772 |
+
performed.
|
773 |
+
|
774 |
+
>>> from mpmath import *
|
775 |
+
>>> mp.dps = 15; mp.pretty = False
|
776 |
+
>>> frexp(7.5)
|
777 |
+
(mpf('0.9375'), 3)
|
778 |
+
|
779 |
+
"""
|
780 |
+
x = ctx.convert(x)
|
781 |
+
y, n = libmp.mpf_frexp(x._mpf_)
|
782 |
+
return ctx.make_mpf(y), n
|
783 |
+
|
784 |
+
def fneg(ctx, x, **kwargs):
|
785 |
+
"""
|
786 |
+
Negates the number *x*, giving a floating-point result, optionally
|
787 |
+
using a custom precision and rounding mode.
|
788 |
+
|
789 |
+
See the documentation of :func:`~mpmath.fadd` for a detailed description
|
790 |
+
of how to specify precision and rounding.
|
791 |
+
|
792 |
+
**Examples**
|
793 |
+
|
794 |
+
An mpmath number is returned::
|
795 |
+
|
796 |
+
>>> from mpmath import *
|
797 |
+
>>> mp.dps = 15; mp.pretty = False
|
798 |
+
>>> fneg(2.5)
|
799 |
+
mpf('-2.5')
|
800 |
+
>>> fneg(-5+2j)
|
801 |
+
mpc(real='5.0', imag='-2.0')
|
802 |
+
|
803 |
+
Precise control over rounding is possible::
|
804 |
+
|
805 |
+
>>> x = fadd(2, 1e-100, exact=True)
|
806 |
+
>>> fneg(x)
|
807 |
+
mpf('-2.0')
|
808 |
+
>>> fneg(x, rounding='f')
|
809 |
+
mpf('-2.0000000000000004')
|
810 |
+
|
811 |
+
Negating with and without roundoff::
|
812 |
+
|
813 |
+
>>> n = 200000000000000000000001
|
814 |
+
>>> print(int(-mpf(n)))
|
815 |
+
-200000000000000016777216
|
816 |
+
>>> print(int(fneg(n)))
|
817 |
+
-200000000000000016777216
|
818 |
+
>>> print(int(fneg(n, prec=log(n,2)+1)))
|
819 |
+
-200000000000000000000001
|
820 |
+
>>> print(int(fneg(n, dps=log(n,10)+1)))
|
821 |
+
-200000000000000000000001
|
822 |
+
>>> print(int(fneg(n, prec=inf)))
|
823 |
+
-200000000000000000000001
|
824 |
+
>>> print(int(fneg(n, dps=inf)))
|
825 |
+
-200000000000000000000001
|
826 |
+
>>> print(int(fneg(n, exact=True)))
|
827 |
+
-200000000000000000000001
|
828 |
+
|
829 |
+
"""
|
830 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
831 |
+
x = ctx.convert(x)
|
832 |
+
if hasattr(x, '_mpf_'):
|
833 |
+
return ctx.make_mpf(mpf_neg(x._mpf_, prec, rounding))
|
834 |
+
if hasattr(x, '_mpc_'):
|
835 |
+
return ctx.make_mpc(mpc_neg(x._mpc_, prec, rounding))
|
836 |
+
raise ValueError("Arguments need to be mpf or mpc compatible numbers")
|
837 |
+
|
838 |
+
def fadd(ctx, x, y, **kwargs):
|
839 |
+
"""
|
840 |
+
Adds the numbers *x* and *y*, giving a floating-point result,
|
841 |
+
optionally using a custom precision and rounding mode.
|
842 |
+
|
843 |
+
The default precision is the working precision of the context.
|
844 |
+
You can specify a custom precision in bits by passing the *prec* keyword
|
845 |
+
argument, or by providing an equivalent decimal precision with the *dps*
|
846 |
+
keyword argument. If the precision is set to ``+inf``, or if the flag
|
847 |
+
*exact=True* is passed, an exact addition with no rounding is performed.
|
848 |
+
|
849 |
+
When the precision is finite, the optional *rounding* keyword argument
|
850 |
+
specifies the direction of rounding. Valid options are ``'n'`` for
|
851 |
+
nearest (default), ``'f'`` for floor, ``'c'`` for ceiling, ``'d'``
|
852 |
+
for down, ``'u'`` for up.
|
853 |
+
|
854 |
+
**Examples**
|
855 |
+
|
856 |
+
Using :func:`~mpmath.fadd` with precision and rounding control::
|
857 |
+
|
858 |
+
>>> from mpmath import *
|
859 |
+
>>> mp.dps = 15; mp.pretty = False
|
860 |
+
>>> fadd(2, 1e-20)
|
861 |
+
mpf('2.0')
|
862 |
+
>>> fadd(2, 1e-20, rounding='u')
|
863 |
+
mpf('2.0000000000000004')
|
864 |
+
>>> nprint(fadd(2, 1e-20, prec=100), 25)
|
865 |
+
2.00000000000000000001
|
866 |
+
>>> nprint(fadd(2, 1e-20, dps=15), 25)
|
867 |
+
2.0
|
868 |
+
>>> nprint(fadd(2, 1e-20, dps=25), 25)
|
869 |
+
2.00000000000000000001
|
870 |
+
>>> nprint(fadd(2, 1e-20, exact=True), 25)
|
871 |
+
2.00000000000000000001
|
872 |
+
|
873 |
+
Exact addition avoids cancellation errors, enforcing familiar laws
|
874 |
+
of numbers such as `x+y-x = y`, which don't hold in floating-point
|
875 |
+
arithmetic with finite precision::
|
876 |
+
|
877 |
+
>>> x, y = mpf(2), mpf('1e-1000')
|
878 |
+
>>> print(x + y - x)
|
879 |
+
0.0
|
880 |
+
>>> print(fadd(x, y, prec=inf) - x)
|
881 |
+
1.0e-1000
|
882 |
+
>>> print(fadd(x, y, exact=True) - x)
|
883 |
+
1.0e-1000
|
884 |
+
|
885 |
+
Exact addition can be inefficient and may be impossible to perform
|
886 |
+
with large magnitude differences::
|
887 |
+
|
888 |
+
>>> fadd(1, '1e-100000000000000000000', prec=inf)
|
889 |
+
Traceback (most recent call last):
|
890 |
+
...
|
891 |
+
OverflowError: the exact result does not fit in memory
|
892 |
+
|
893 |
+
"""
|
894 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
895 |
+
x = ctx.convert(x)
|
896 |
+
y = ctx.convert(y)
|
897 |
+
try:
|
898 |
+
if hasattr(x, '_mpf_'):
|
899 |
+
if hasattr(y, '_mpf_'):
|
900 |
+
return ctx.make_mpf(mpf_add(x._mpf_, y._mpf_, prec, rounding))
|
901 |
+
if hasattr(y, '_mpc_'):
|
902 |
+
return ctx.make_mpc(mpc_add_mpf(y._mpc_, x._mpf_, prec, rounding))
|
903 |
+
if hasattr(x, '_mpc_'):
|
904 |
+
if hasattr(y, '_mpf_'):
|
905 |
+
return ctx.make_mpc(mpc_add_mpf(x._mpc_, y._mpf_, prec, rounding))
|
906 |
+
if hasattr(y, '_mpc_'):
|
907 |
+
return ctx.make_mpc(mpc_add(x._mpc_, y._mpc_, prec, rounding))
|
908 |
+
except (ValueError, OverflowError):
|
909 |
+
raise OverflowError(ctx._exact_overflow_msg)
|
910 |
+
raise ValueError("Arguments need to be mpf or mpc compatible numbers")
|
911 |
+
|
912 |
+
def fsub(ctx, x, y, **kwargs):
|
913 |
+
"""
|
914 |
+
Subtracts the numbers *x* and *y*, giving a floating-point result,
|
915 |
+
optionally using a custom precision and rounding mode.
|
916 |
+
|
917 |
+
See the documentation of :func:`~mpmath.fadd` for a detailed description
|
918 |
+
of how to specify precision and rounding.
|
919 |
+
|
920 |
+
**Examples**
|
921 |
+
|
922 |
+
Using :func:`~mpmath.fsub` with precision and rounding control::
|
923 |
+
|
924 |
+
>>> from mpmath import *
|
925 |
+
>>> mp.dps = 15; mp.pretty = False
|
926 |
+
>>> fsub(2, 1e-20)
|
927 |
+
mpf('2.0')
|
928 |
+
>>> fsub(2, 1e-20, rounding='d')
|
929 |
+
mpf('1.9999999999999998')
|
930 |
+
>>> nprint(fsub(2, 1e-20, prec=100), 25)
|
931 |
+
1.99999999999999999999
|
932 |
+
>>> nprint(fsub(2, 1e-20, dps=15), 25)
|
933 |
+
2.0
|
934 |
+
>>> nprint(fsub(2, 1e-20, dps=25), 25)
|
935 |
+
1.99999999999999999999
|
936 |
+
>>> nprint(fsub(2, 1e-20, exact=True), 25)
|
937 |
+
1.99999999999999999999
|
938 |
+
|
939 |
+
Exact subtraction avoids cancellation errors, enforcing familiar laws
|
940 |
+
of numbers such as `x-y+y = x`, which don't hold in floating-point
|
941 |
+
arithmetic with finite precision::
|
942 |
+
|
943 |
+
>>> x, y = mpf(2), mpf('1e1000')
|
944 |
+
>>> print(x - y + y)
|
945 |
+
0.0
|
946 |
+
>>> print(fsub(x, y, prec=inf) + y)
|
947 |
+
2.0
|
948 |
+
>>> print(fsub(x, y, exact=True) + y)
|
949 |
+
2.0
|
950 |
+
|
951 |
+
Exact addition can be inefficient and may be impossible to perform
|
952 |
+
with large magnitude differences::
|
953 |
+
|
954 |
+
>>> fsub(1, '1e-100000000000000000000', prec=inf)
|
955 |
+
Traceback (most recent call last):
|
956 |
+
...
|
957 |
+
OverflowError: the exact result does not fit in memory
|
958 |
+
|
959 |
+
"""
|
960 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
961 |
+
x = ctx.convert(x)
|
962 |
+
y = ctx.convert(y)
|
963 |
+
try:
|
964 |
+
if hasattr(x, '_mpf_'):
|
965 |
+
if hasattr(y, '_mpf_'):
|
966 |
+
return ctx.make_mpf(mpf_sub(x._mpf_, y._mpf_, prec, rounding))
|
967 |
+
if hasattr(y, '_mpc_'):
|
968 |
+
return ctx.make_mpc(mpc_sub((x._mpf_, fzero), y._mpc_, prec, rounding))
|
969 |
+
if hasattr(x, '_mpc_'):
|
970 |
+
if hasattr(y, '_mpf_'):
|
971 |
+
return ctx.make_mpc(mpc_sub_mpf(x._mpc_, y._mpf_, prec, rounding))
|
972 |
+
if hasattr(y, '_mpc_'):
|
973 |
+
return ctx.make_mpc(mpc_sub(x._mpc_, y._mpc_, prec, rounding))
|
974 |
+
except (ValueError, OverflowError):
|
975 |
+
raise OverflowError(ctx._exact_overflow_msg)
|
976 |
+
raise ValueError("Arguments need to be mpf or mpc compatible numbers")
|
977 |
+
|
978 |
+
def fmul(ctx, x, y, **kwargs):
|
979 |
+
"""
|
980 |
+
Multiplies the numbers *x* and *y*, giving a floating-point result,
|
981 |
+
optionally using a custom precision and rounding mode.
|
982 |
+
|
983 |
+
See the documentation of :func:`~mpmath.fadd` for a detailed description
|
984 |
+
of how to specify precision and rounding.
|
985 |
+
|
986 |
+
**Examples**
|
987 |
+
|
988 |
+
The result is an mpmath number::
|
989 |
+
|
990 |
+
>>> from mpmath import *
|
991 |
+
>>> mp.dps = 15; mp.pretty = False
|
992 |
+
>>> fmul(2, 5.0)
|
993 |
+
mpf('10.0')
|
994 |
+
>>> fmul(0.5j, 0.5)
|
995 |
+
mpc(real='0.0', imag='0.25')
|
996 |
+
|
997 |
+
Avoiding roundoff::
|
998 |
+
|
999 |
+
>>> x, y = 10**10+1, 10**15+1
|
1000 |
+
>>> print(x*y)
|
1001 |
+
10000000001000010000000001
|
1002 |
+
>>> print(mpf(x) * mpf(y))
|
1003 |
+
1.0000000001e+25
|
1004 |
+
>>> print(int(mpf(x) * mpf(y)))
|
1005 |
+
10000000001000011026399232
|
1006 |
+
>>> print(int(fmul(x, y)))
|
1007 |
+
10000000001000011026399232
|
1008 |
+
>>> print(int(fmul(x, y, dps=25)))
|
1009 |
+
10000000001000010000000001
|
1010 |
+
>>> print(int(fmul(x, y, exact=True)))
|
1011 |
+
10000000001000010000000001
|
1012 |
+
|
1013 |
+
Exact multiplication with complex numbers can be inefficient and may
|
1014 |
+
be impossible to perform with large magnitude differences between
|
1015 |
+
real and imaginary parts::
|
1016 |
+
|
1017 |
+
>>> x = 1+2j
|
1018 |
+
>>> y = mpc(2, '1e-100000000000000000000')
|
1019 |
+
>>> fmul(x, y)
|
1020 |
+
mpc(real='2.0', imag='4.0')
|
1021 |
+
>>> fmul(x, y, rounding='u')
|
1022 |
+
mpc(real='2.0', imag='4.0000000000000009')
|
1023 |
+
>>> fmul(x, y, exact=True)
|
1024 |
+
Traceback (most recent call last):
|
1025 |
+
...
|
1026 |
+
OverflowError: the exact result does not fit in memory
|
1027 |
+
|
1028 |
+
"""
|
1029 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
1030 |
+
x = ctx.convert(x)
|
1031 |
+
y = ctx.convert(y)
|
1032 |
+
try:
|
1033 |
+
if hasattr(x, '_mpf_'):
|
1034 |
+
if hasattr(y, '_mpf_'):
|
1035 |
+
return ctx.make_mpf(mpf_mul(x._mpf_, y._mpf_, prec, rounding))
|
1036 |
+
if hasattr(y, '_mpc_'):
|
1037 |
+
return ctx.make_mpc(mpc_mul_mpf(y._mpc_, x._mpf_, prec, rounding))
|
1038 |
+
if hasattr(x, '_mpc_'):
|
1039 |
+
if hasattr(y, '_mpf_'):
|
1040 |
+
return ctx.make_mpc(mpc_mul_mpf(x._mpc_, y._mpf_, prec, rounding))
|
1041 |
+
if hasattr(y, '_mpc_'):
|
1042 |
+
return ctx.make_mpc(mpc_mul(x._mpc_, y._mpc_, prec, rounding))
|
1043 |
+
except (ValueError, OverflowError):
|
1044 |
+
raise OverflowError(ctx._exact_overflow_msg)
|
1045 |
+
raise ValueError("Arguments need to be mpf or mpc compatible numbers")
|
1046 |
+
|
1047 |
+
def fdiv(ctx, x, y, **kwargs):
|
1048 |
+
"""
|
1049 |
+
Divides the numbers *x* and *y*, giving a floating-point result,
|
1050 |
+
optionally using a custom precision and rounding mode.
|
1051 |
+
|
1052 |
+
See the documentation of :func:`~mpmath.fadd` for a detailed description
|
1053 |
+
of how to specify precision and rounding.
|
1054 |
+
|
1055 |
+
**Examples**
|
1056 |
+
|
1057 |
+
The result is an mpmath number::
|
1058 |
+
|
1059 |
+
>>> from mpmath import *
|
1060 |
+
>>> mp.dps = 15; mp.pretty = False
|
1061 |
+
>>> fdiv(3, 2)
|
1062 |
+
mpf('1.5')
|
1063 |
+
>>> fdiv(2, 3)
|
1064 |
+
mpf('0.66666666666666663')
|
1065 |
+
>>> fdiv(2+4j, 0.5)
|
1066 |
+
mpc(real='4.0', imag='8.0')
|
1067 |
+
|
1068 |
+
The rounding direction and precision can be controlled::
|
1069 |
+
|
1070 |
+
>>> fdiv(2, 3, dps=3) # Should be accurate to at least 3 digits
|
1071 |
+
mpf('0.6666259765625')
|
1072 |
+
>>> fdiv(2, 3, rounding='d')
|
1073 |
+
mpf('0.66666666666666663')
|
1074 |
+
>>> fdiv(2, 3, prec=60)
|
1075 |
+
mpf('0.66666666666666667')
|
1076 |
+
>>> fdiv(2, 3, rounding='u')
|
1077 |
+
mpf('0.66666666666666674')
|
1078 |
+
|
1079 |
+
Checking the error of a division by performing it at higher precision::
|
1080 |
+
|
1081 |
+
>>> fdiv(2, 3) - fdiv(2, 3, prec=100)
|
1082 |
+
mpf('-3.7007434154172148e-17')
|
1083 |
+
|
1084 |
+
Unlike :func:`~mpmath.fadd`, :func:`~mpmath.fmul`, etc., exact division is not
|
1085 |
+
allowed since the quotient of two floating-point numbers generally
|
1086 |
+
does not have an exact floating-point representation. (In the
|
1087 |
+
future this might be changed to allow the case where the division
|
1088 |
+
is actually exact.)
|
1089 |
+
|
1090 |
+
>>> fdiv(2, 3, exact=True)
|
1091 |
+
Traceback (most recent call last):
|
1092 |
+
...
|
1093 |
+
ValueError: division is not an exact operation
|
1094 |
+
|
1095 |
+
"""
|
1096 |
+
prec, rounding = ctx._parse_prec(kwargs)
|
1097 |
+
if not prec:
|
1098 |
+
raise ValueError("division is not an exact operation")
|
1099 |
+
x = ctx.convert(x)
|
1100 |
+
y = ctx.convert(y)
|
1101 |
+
if hasattr(x, '_mpf_'):
|
1102 |
+
if hasattr(y, '_mpf_'):
|
1103 |
+
return ctx.make_mpf(mpf_div(x._mpf_, y._mpf_, prec, rounding))
|
1104 |
+
if hasattr(y, '_mpc_'):
|
1105 |
+
return ctx.make_mpc(mpc_div((x._mpf_, fzero), y._mpc_, prec, rounding))
|
1106 |
+
if hasattr(x, '_mpc_'):
|
1107 |
+
if hasattr(y, '_mpf_'):
|
1108 |
+
return ctx.make_mpc(mpc_div_mpf(x._mpc_, y._mpf_, prec, rounding))
|
1109 |
+
if hasattr(y, '_mpc_'):
|
1110 |
+
return ctx.make_mpc(mpc_div(x._mpc_, y._mpc_, prec, rounding))
|
1111 |
+
raise ValueError("Arguments need to be mpf or mpc compatible numbers")
|
1112 |
+
|
1113 |
+
def nint_distance(ctx, x):
|
1114 |
+
r"""
|
1115 |
+
Return `(n,d)` where `n` is the nearest integer to `x` and `d` is
|
1116 |
+
an estimate of `\log_2(|x-n|)`. If `d < 0`, `-d` gives the precision
|
1117 |
+
(measured in bits) lost to cancellation when computing `x-n`.
|
1118 |
+
|
1119 |
+
>>> from mpmath import *
|
1120 |
+
>>> n, d = nint_distance(5)
|
1121 |
+
>>> print(n); print(d)
|
1122 |
+
5
|
1123 |
+
-inf
|
1124 |
+
>>> n, d = nint_distance(mpf(5))
|
1125 |
+
>>> print(n); print(d)
|
1126 |
+
5
|
1127 |
+
-inf
|
1128 |
+
>>> n, d = nint_distance(mpf(5.00000001))
|
1129 |
+
>>> print(n); print(d)
|
1130 |
+
5
|
1131 |
+
-26
|
1132 |
+
>>> n, d = nint_distance(mpf(4.99999999))
|
1133 |
+
>>> print(n); print(d)
|
1134 |
+
5
|
1135 |
+
-26
|
1136 |
+
>>> n, d = nint_distance(mpc(5,10))
|
1137 |
+
>>> print(n); print(d)
|
1138 |
+
5
|
1139 |
+
4
|
1140 |
+
>>> n, d = nint_distance(mpc(5,0.000001))
|
1141 |
+
>>> print(n); print(d)
|
1142 |
+
5
|
1143 |
+
-19
|
1144 |
+
|
1145 |
+
"""
|
1146 |
+
typx = type(x)
|
1147 |
+
if typx in int_types:
|
1148 |
+
return int(x), ctx.ninf
|
1149 |
+
elif typx is rational.mpq:
|
1150 |
+
p, q = x._mpq_
|
1151 |
+
n, r = divmod(p, q)
|
1152 |
+
if 2*r >= q:
|
1153 |
+
n += 1
|
1154 |
+
elif not r:
|
1155 |
+
return n, ctx.ninf
|
1156 |
+
# log(p/q-n) = log((p-nq)/q) = log(p-nq) - log(q)
|
1157 |
+
d = bitcount(abs(p-n*q)) - bitcount(q)
|
1158 |
+
return n, d
|
1159 |
+
if hasattr(x, "_mpf_"):
|
1160 |
+
re = x._mpf_
|
1161 |
+
im_dist = ctx.ninf
|
1162 |
+
elif hasattr(x, "_mpc_"):
|
1163 |
+
re, im = x._mpc_
|
1164 |
+
isign, iman, iexp, ibc = im
|
1165 |
+
if iman:
|
1166 |
+
im_dist = iexp + ibc
|
1167 |
+
elif im == fzero:
|
1168 |
+
im_dist = ctx.ninf
|
1169 |
+
else:
|
1170 |
+
raise ValueError("requires a finite number")
|
1171 |
+
else:
|
1172 |
+
x = ctx.convert(x)
|
1173 |
+
if hasattr(x, "_mpf_") or hasattr(x, "_mpc_"):
|
1174 |
+
return ctx.nint_distance(x)
|
1175 |
+
else:
|
1176 |
+
raise TypeError("requires an mpf/mpc")
|
1177 |
+
sign, man, exp, bc = re
|
1178 |
+
mag = exp+bc
|
1179 |
+
# |x| < 0.5
|
1180 |
+
if mag < 0:
|
1181 |
+
n = 0
|
1182 |
+
re_dist = mag
|
1183 |
+
elif man:
|
1184 |
+
# exact integer
|
1185 |
+
if exp >= 0:
|
1186 |
+
n = man << exp
|
1187 |
+
re_dist = ctx.ninf
|
1188 |
+
# exact half-integer
|
1189 |
+
elif exp == -1:
|
1190 |
+
n = (man>>1)+1
|
1191 |
+
re_dist = 0
|
1192 |
+
else:
|
1193 |
+
d = (-exp-1)
|
1194 |
+
t = man >> d
|
1195 |
+
if t & 1:
|
1196 |
+
t += 1
|
1197 |
+
man = (t<<d) - man
|
1198 |
+
else:
|
1199 |
+
man -= (t<<d)
|
1200 |
+
n = t>>1 # int(t)>>1
|
1201 |
+
re_dist = exp+bitcount(man)
|
1202 |
+
if sign:
|
1203 |
+
n = -n
|
1204 |
+
elif re == fzero:
|
1205 |
+
re_dist = ctx.ninf
|
1206 |
+
n = 0
|
1207 |
+
else:
|
1208 |
+
raise ValueError("requires a finite number")
|
1209 |
+
return n, max(re_dist, im_dist)
|
1210 |
+
|
1211 |
+
def fprod(ctx, factors):
|
1212 |
+
r"""
|
1213 |
+
Calculates a product containing a finite number of factors (for
|
1214 |
+
infinite products, see :func:`~mpmath.nprod`). The factors will be
|
1215 |
+
converted to mpmath numbers.
|
1216 |
+
|
1217 |
+
>>> from mpmath import *
|
1218 |
+
>>> mp.dps = 15; mp.pretty = False
|
1219 |
+
>>> fprod([1, 2, 0.5, 7])
|
1220 |
+
mpf('7.0')
|
1221 |
+
|
1222 |
+
"""
|
1223 |
+
orig = ctx.prec
|
1224 |
+
try:
|
1225 |
+
v = ctx.one
|
1226 |
+
for p in factors:
|
1227 |
+
v *= p
|
1228 |
+
finally:
|
1229 |
+
ctx.prec = orig
|
1230 |
+
return +v
|
1231 |
+
|
1232 |
+
def rand(ctx):
|
1233 |
+
"""
|
1234 |
+
Returns an ``mpf`` with value chosen randomly from `[0, 1)`.
|
1235 |
+
The number of randomly generated bits in the mantissa is equal
|
1236 |
+
to the working precision.
|
1237 |
+
"""
|
1238 |
+
return ctx.make_mpf(mpf_rand(ctx._prec))
|
1239 |
+
|
1240 |
+
def fraction(ctx, p, q):
|
1241 |
+
"""
|
1242 |
+
Given Python integers `(p, q)`, returns a lazy ``mpf`` representing
|
1243 |
+
the fraction `p/q`. The value is updated with the precision.
|
1244 |
+
|
1245 |
+
>>> from mpmath import *
|
1246 |
+
>>> mp.dps = 15
|
1247 |
+
>>> a = fraction(1,100)
|
1248 |
+
>>> b = mpf(1)/100
|
1249 |
+
>>> print(a); print(b)
|
1250 |
+
0.01
|
1251 |
+
0.01
|
1252 |
+
>>> mp.dps = 30
|
1253 |
+
>>> print(a); print(b) # a will be accurate
|
1254 |
+
0.01
|
1255 |
+
0.0100000000000000002081668171172
|
1256 |
+
>>> mp.dps = 15
|
1257 |
+
"""
|
1258 |
+
return ctx.constant(lambda prec, rnd: from_rational(p, q, prec, rnd),
|
1259 |
+
'%s/%s' % (p, q))
|
1260 |
+
|
1261 |
+
def absmin(ctx, x):
|
1262 |
+
return abs(ctx.convert(x))
|
1263 |
+
|
1264 |
+
def absmax(ctx, x):
|
1265 |
+
return abs(ctx.convert(x))
|
1266 |
+
|
1267 |
+
def _as_points(ctx, x):
|
1268 |
+
# XXX: remove this?
|
1269 |
+
if hasattr(x, '_mpi_'):
|
1270 |
+
a, b = x._mpi_
|
1271 |
+
return [ctx.make_mpf(a), ctx.make_mpf(b)]
|
1272 |
+
return x
|
1273 |
+
|
1274 |
+
'''
|
1275 |
+
def _zetasum(ctx, s, a, b):
|
1276 |
+
"""
|
1277 |
+
Computes sum of k^(-s) for k = a, a+1, ..., b with a, b both small
|
1278 |
+
integers.
|
1279 |
+
"""
|
1280 |
+
a = int(a)
|
1281 |
+
b = int(b)
|
1282 |
+
s = ctx.convert(s)
|
1283 |
+
prec, rounding = ctx._prec_rounding
|
1284 |
+
if hasattr(s, '_mpf_'):
|
1285 |
+
v = ctx.make_mpf(libmp.mpf_zetasum(s._mpf_, a, b, prec))
|
1286 |
+
elif hasattr(s, '_mpc_'):
|
1287 |
+
v = ctx.make_mpc(libmp.mpc_zetasum(s._mpc_, a, b, prec))
|
1288 |
+
return v
|
1289 |
+
'''
|
1290 |
+
|
1291 |
+
def _zetasum_fast(ctx, s, a, n, derivatives=[0], reflect=False):
|
1292 |
+
if not (ctx.isint(a) and hasattr(s, "_mpc_")):
|
1293 |
+
raise NotImplementedError
|
1294 |
+
a = int(a)
|
1295 |
+
prec = ctx._prec
|
1296 |
+
xs, ys = libmp.mpc_zetasum(s._mpc_, a, n, derivatives, reflect, prec)
|
1297 |
+
xs = [ctx.make_mpc(x) for x in xs]
|
1298 |
+
ys = [ctx.make_mpc(y) for y in ys]
|
1299 |
+
return xs, ys
|
1300 |
+
|
1301 |
+
class PrecisionManager:
|
1302 |
+
def __init__(self, ctx, precfun, dpsfun, normalize_output=False):
|
1303 |
+
self.ctx = ctx
|
1304 |
+
self.precfun = precfun
|
1305 |
+
self.dpsfun = dpsfun
|
1306 |
+
self.normalize_output = normalize_output
|
1307 |
+
def __call__(self, f):
|
1308 |
+
@functools.wraps(f)
|
1309 |
+
def g(*args, **kwargs):
|
1310 |
+
orig = self.ctx.prec
|
1311 |
+
try:
|
1312 |
+
if self.precfun:
|
1313 |
+
self.ctx.prec = self.precfun(self.ctx.prec)
|
1314 |
+
else:
|
1315 |
+
self.ctx.dps = self.dpsfun(self.ctx.dps)
|
1316 |
+
if self.normalize_output:
|
1317 |
+
v = f(*args, **kwargs)
|
1318 |
+
if type(v) is tuple:
|
1319 |
+
return tuple([+a for a in v])
|
1320 |
+
return +v
|
1321 |
+
else:
|
1322 |
+
return f(*args, **kwargs)
|
1323 |
+
finally:
|
1324 |
+
self.ctx.prec = orig
|
1325 |
+
return g
|
1326 |
+
def __enter__(self):
|
1327 |
+
self.origp = self.ctx.prec
|
1328 |
+
if self.precfun:
|
1329 |
+
self.ctx.prec = self.precfun(self.ctx.prec)
|
1330 |
+
else:
|
1331 |
+
self.ctx.dps = self.dpsfun(self.ctx.dps)
|
1332 |
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
1333 |
+
self.ctx.prec = self.origp
|
1334 |
+
return False
|
1335 |
+
|
1336 |
+
|
1337 |
+
if __name__ == '__main__':
|
1338 |
+
import doctest
|
1339 |
+
doctest.testmod()
|
env-llmeval/lib/python3.10/site-packages/mpmath/function_docs.py
ADDED
The diff for this file is too large to render.
See raw diff
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/math2.py
ADDED
@@ -0,0 +1,672 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
This module complements the math and cmath builtin modules by providing
|
3 |
+
fast machine precision versions of some additional functions (gamma, ...)
|
4 |
+
and wrapping math/cmath functions so that they can be called with either
|
5 |
+
real or complex arguments.
|
6 |
+
"""
|
7 |
+
|
8 |
+
import operator
|
9 |
+
import math
|
10 |
+
import cmath
|
11 |
+
|
12 |
+
# Irrational (?) constants
|
13 |
+
pi = 3.1415926535897932385
|
14 |
+
e = 2.7182818284590452354
|
15 |
+
sqrt2 = 1.4142135623730950488
|
16 |
+
sqrt5 = 2.2360679774997896964
|
17 |
+
phi = 1.6180339887498948482
|
18 |
+
ln2 = 0.69314718055994530942
|
19 |
+
ln10 = 2.302585092994045684
|
20 |
+
euler = 0.57721566490153286061
|
21 |
+
catalan = 0.91596559417721901505
|
22 |
+
khinchin = 2.6854520010653064453
|
23 |
+
apery = 1.2020569031595942854
|
24 |
+
|
25 |
+
logpi = 1.1447298858494001741
|
26 |
+
|
27 |
+
def _mathfun_real(f_real, f_complex):
|
28 |
+
def f(x, **kwargs):
|
29 |
+
if type(x) is float:
|
30 |
+
return f_real(x)
|
31 |
+
if type(x) is complex:
|
32 |
+
return f_complex(x)
|
33 |
+
try:
|
34 |
+
x = float(x)
|
35 |
+
return f_real(x)
|
36 |
+
except (TypeError, ValueError):
|
37 |
+
x = complex(x)
|
38 |
+
return f_complex(x)
|
39 |
+
f.__name__ = f_real.__name__
|
40 |
+
return f
|
41 |
+
|
42 |
+
def _mathfun(f_real, f_complex):
|
43 |
+
def f(x, **kwargs):
|
44 |
+
if type(x) is complex:
|
45 |
+
return f_complex(x)
|
46 |
+
try:
|
47 |
+
return f_real(float(x))
|
48 |
+
except (TypeError, ValueError):
|
49 |
+
return f_complex(complex(x))
|
50 |
+
f.__name__ = f_real.__name__
|
51 |
+
return f
|
52 |
+
|
53 |
+
def _mathfun_n(f_real, f_complex):
|
54 |
+
def f(*args, **kwargs):
|
55 |
+
try:
|
56 |
+
return f_real(*(float(x) for x in args))
|
57 |
+
except (TypeError, ValueError):
|
58 |
+
return f_complex(*(complex(x) for x in args))
|
59 |
+
f.__name__ = f_real.__name__
|
60 |
+
return f
|
61 |
+
|
62 |
+
# Workaround for non-raising log and sqrt in Python 2.5 and 2.4
|
63 |
+
# on Unix system
|
64 |
+
try:
|
65 |
+
math.log(-2.0)
|
66 |
+
def math_log(x):
|
67 |
+
if x <= 0.0:
|
68 |
+
raise ValueError("math domain error")
|
69 |
+
return math.log(x)
|
70 |
+
def math_sqrt(x):
|
71 |
+
if x < 0.0:
|
72 |
+
raise ValueError("math domain error")
|
73 |
+
return math.sqrt(x)
|
74 |
+
except (ValueError, TypeError):
|
75 |
+
math_log = math.log
|
76 |
+
math_sqrt = math.sqrt
|
77 |
+
|
78 |
+
pow = _mathfun_n(operator.pow, lambda x, y: complex(x)**y)
|
79 |
+
log = _mathfun_n(math_log, cmath.log)
|
80 |
+
sqrt = _mathfun(math_sqrt, cmath.sqrt)
|
81 |
+
exp = _mathfun_real(math.exp, cmath.exp)
|
82 |
+
|
83 |
+
cos = _mathfun_real(math.cos, cmath.cos)
|
84 |
+
sin = _mathfun_real(math.sin, cmath.sin)
|
85 |
+
tan = _mathfun_real(math.tan, cmath.tan)
|
86 |
+
|
87 |
+
acos = _mathfun(math.acos, cmath.acos)
|
88 |
+
asin = _mathfun(math.asin, cmath.asin)
|
89 |
+
atan = _mathfun_real(math.atan, cmath.atan)
|
90 |
+
|
91 |
+
cosh = _mathfun_real(math.cosh, cmath.cosh)
|
92 |
+
sinh = _mathfun_real(math.sinh, cmath.sinh)
|
93 |
+
tanh = _mathfun_real(math.tanh, cmath.tanh)
|
94 |
+
|
95 |
+
floor = _mathfun_real(math.floor,
|
96 |
+
lambda z: complex(math.floor(z.real), math.floor(z.imag)))
|
97 |
+
ceil = _mathfun_real(math.ceil,
|
98 |
+
lambda z: complex(math.ceil(z.real), math.ceil(z.imag)))
|
99 |
+
|
100 |
+
|
101 |
+
cos_sin = _mathfun_real(lambda x: (math.cos(x), math.sin(x)),
|
102 |
+
lambda z: (cmath.cos(z), cmath.sin(z)))
|
103 |
+
|
104 |
+
cbrt = _mathfun(lambda x: x**(1./3), lambda z: z**(1./3))
|
105 |
+
|
106 |
+
def nthroot(x, n):
|
107 |
+
r = 1./n
|
108 |
+
try:
|
109 |
+
return float(x) ** r
|
110 |
+
except (ValueError, TypeError):
|
111 |
+
return complex(x) ** r
|
112 |
+
|
113 |
+
def _sinpi_real(x):
|
114 |
+
if x < 0:
|
115 |
+
return -_sinpi_real(-x)
|
116 |
+
n, r = divmod(x, 0.5)
|
117 |
+
r *= pi
|
118 |
+
n %= 4
|
119 |
+
if n == 0: return math.sin(r)
|
120 |
+
if n == 1: return math.cos(r)
|
121 |
+
if n == 2: return -math.sin(r)
|
122 |
+
if n == 3: return -math.cos(r)
|
123 |
+
|
124 |
+
def _cospi_real(x):
|
125 |
+
if x < 0:
|
126 |
+
x = -x
|
127 |
+
n, r = divmod(x, 0.5)
|
128 |
+
r *= pi
|
129 |
+
n %= 4
|
130 |
+
if n == 0: return math.cos(r)
|
131 |
+
if n == 1: return -math.sin(r)
|
132 |
+
if n == 2: return -math.cos(r)
|
133 |
+
if n == 3: return math.sin(r)
|
134 |
+
|
135 |
+
def _sinpi_complex(z):
|
136 |
+
if z.real < 0:
|
137 |
+
return -_sinpi_complex(-z)
|
138 |
+
n, r = divmod(z.real, 0.5)
|
139 |
+
z = pi*complex(r, z.imag)
|
140 |
+
n %= 4
|
141 |
+
if n == 0: return cmath.sin(z)
|
142 |
+
if n == 1: return cmath.cos(z)
|
143 |
+
if n == 2: return -cmath.sin(z)
|
144 |
+
if n == 3: return -cmath.cos(z)
|
145 |
+
|
146 |
+
def _cospi_complex(z):
|
147 |
+
if z.real < 0:
|
148 |
+
z = -z
|
149 |
+
n, r = divmod(z.real, 0.5)
|
150 |
+
z = pi*complex(r, z.imag)
|
151 |
+
n %= 4
|
152 |
+
if n == 0: return cmath.cos(z)
|
153 |
+
if n == 1: return -cmath.sin(z)
|
154 |
+
if n == 2: return -cmath.cos(z)
|
155 |
+
if n == 3: return cmath.sin(z)
|
156 |
+
|
157 |
+
cospi = _mathfun_real(_cospi_real, _cospi_complex)
|
158 |
+
sinpi = _mathfun_real(_sinpi_real, _sinpi_complex)
|
159 |
+
|
160 |
+
def tanpi(x):
|
161 |
+
try:
|
162 |
+
return sinpi(x) / cospi(x)
|
163 |
+
except OverflowError:
|
164 |
+
if complex(x).imag > 10:
|
165 |
+
return 1j
|
166 |
+
if complex(x).imag < 10:
|
167 |
+
return -1j
|
168 |
+
raise
|
169 |
+
|
170 |
+
def cotpi(x):
|
171 |
+
try:
|
172 |
+
return cospi(x) / sinpi(x)
|
173 |
+
except OverflowError:
|
174 |
+
if complex(x).imag > 10:
|
175 |
+
return -1j
|
176 |
+
if complex(x).imag < 10:
|
177 |
+
return 1j
|
178 |
+
raise
|
179 |
+
|
180 |
+
INF = 1e300*1e300
|
181 |
+
NINF = -INF
|
182 |
+
NAN = INF-INF
|
183 |
+
EPS = 2.2204460492503131e-16
|
184 |
+
|
185 |
+
_exact_gamma = (INF, 1.0, 1.0, 2.0, 6.0, 24.0, 120.0, 720.0, 5040.0, 40320.0,
|
186 |
+
362880.0, 3628800.0, 39916800.0, 479001600.0, 6227020800.0, 87178291200.0,
|
187 |
+
1307674368000.0, 20922789888000.0, 355687428096000.0, 6402373705728000.0,
|
188 |
+
121645100408832000.0, 2432902008176640000.0)
|
189 |
+
|
190 |
+
_max_exact_gamma = len(_exact_gamma)-1
|
191 |
+
|
192 |
+
# Lanczos coefficients used by the GNU Scientific Library
|
193 |
+
_lanczos_g = 7
|
194 |
+
_lanczos_p = (0.99999999999980993, 676.5203681218851, -1259.1392167224028,
|
195 |
+
771.32342877765313, -176.61502916214059, 12.507343278686905,
|
196 |
+
-0.13857109526572012, 9.9843695780195716e-6, 1.5056327351493116e-7)
|
197 |
+
|
198 |
+
def _gamma_real(x):
|
199 |
+
_intx = int(x)
|
200 |
+
if _intx == x:
|
201 |
+
if _intx <= 0:
|
202 |
+
#return (-1)**_intx * INF
|
203 |
+
raise ZeroDivisionError("gamma function pole")
|
204 |
+
if _intx <= _max_exact_gamma:
|
205 |
+
return _exact_gamma[_intx]
|
206 |
+
if x < 0.5:
|
207 |
+
# TODO: sinpi
|
208 |
+
return pi / (_sinpi_real(x)*_gamma_real(1-x))
|
209 |
+
else:
|
210 |
+
x -= 1.0
|
211 |
+
r = _lanczos_p[0]
|
212 |
+
for i in range(1, _lanczos_g+2):
|
213 |
+
r += _lanczos_p[i]/(x+i)
|
214 |
+
t = x + _lanczos_g + 0.5
|
215 |
+
return 2.506628274631000502417 * t**(x+0.5) * math.exp(-t) * r
|
216 |
+
|
217 |
+
def _gamma_complex(x):
|
218 |
+
if not x.imag:
|
219 |
+
return complex(_gamma_real(x.real))
|
220 |
+
if x.real < 0.5:
|
221 |
+
# TODO: sinpi
|
222 |
+
return pi / (_sinpi_complex(x)*_gamma_complex(1-x))
|
223 |
+
else:
|
224 |
+
x -= 1.0
|
225 |
+
r = _lanczos_p[0]
|
226 |
+
for i in range(1, _lanczos_g+2):
|
227 |
+
r += _lanczos_p[i]/(x+i)
|
228 |
+
t = x + _lanczos_g + 0.5
|
229 |
+
return 2.506628274631000502417 * t**(x+0.5) * cmath.exp(-t) * r
|
230 |
+
|
231 |
+
gamma = _mathfun_real(_gamma_real, _gamma_complex)
|
232 |
+
|
233 |
+
def rgamma(x):
|
234 |
+
try:
|
235 |
+
return 1./gamma(x)
|
236 |
+
except ZeroDivisionError:
|
237 |
+
return x*0.0
|
238 |
+
|
239 |
+
def factorial(x):
|
240 |
+
return gamma(x+1.0)
|
241 |
+
|
242 |
+
def arg(x):
|
243 |
+
if type(x) is float:
|
244 |
+
return math.atan2(0.0,x)
|
245 |
+
return math.atan2(x.imag,x.real)
|
246 |
+
|
247 |
+
# XXX: broken for negatives
|
248 |
+
def loggamma(x):
|
249 |
+
if type(x) not in (float, complex):
|
250 |
+
try:
|
251 |
+
x = float(x)
|
252 |
+
except (ValueError, TypeError):
|
253 |
+
x = complex(x)
|
254 |
+
try:
|
255 |
+
xreal = x.real
|
256 |
+
ximag = x.imag
|
257 |
+
except AttributeError: # py2.5
|
258 |
+
xreal = x
|
259 |
+
ximag = 0.0
|
260 |
+
# Reflection formula
|
261 |
+
# http://functions.wolfram.com/GammaBetaErf/LogGamma/16/01/01/0003/
|
262 |
+
if xreal < 0.0:
|
263 |
+
if abs(x) < 0.5:
|
264 |
+
v = log(gamma(x))
|
265 |
+
if ximag == 0:
|
266 |
+
v = v.conjugate()
|
267 |
+
return v
|
268 |
+
z = 1-x
|
269 |
+
try:
|
270 |
+
re = z.real
|
271 |
+
im = z.imag
|
272 |
+
except AttributeError: # py2.5
|
273 |
+
re = z
|
274 |
+
im = 0.0
|
275 |
+
refloor = floor(re)
|
276 |
+
if im == 0.0:
|
277 |
+
imsign = 0
|
278 |
+
elif im < 0.0:
|
279 |
+
imsign = -1
|
280 |
+
else:
|
281 |
+
imsign = 1
|
282 |
+
return (-pi*1j)*abs(refloor)*(1-abs(imsign)) + logpi - \
|
283 |
+
log(sinpi(z-refloor)) - loggamma(z) + 1j*pi*refloor*imsign
|
284 |
+
if x == 1.0 or x == 2.0:
|
285 |
+
return x*0
|
286 |
+
p = 0.
|
287 |
+
while abs(x) < 11:
|
288 |
+
p -= log(x)
|
289 |
+
x += 1.0
|
290 |
+
s = 0.918938533204672742 + (x-0.5)*log(x) - x
|
291 |
+
r = 1./x
|
292 |
+
r2 = r*r
|
293 |
+
s += 0.083333333333333333333*r; r *= r2
|
294 |
+
s += -0.0027777777777777777778*r; r *= r2
|
295 |
+
s += 0.00079365079365079365079*r; r *= r2
|
296 |
+
s += -0.0005952380952380952381*r; r *= r2
|
297 |
+
s += 0.00084175084175084175084*r; r *= r2
|
298 |
+
s += -0.0019175269175269175269*r; r *= r2
|
299 |
+
s += 0.0064102564102564102564*r; r *= r2
|
300 |
+
s += -0.02955065359477124183*r
|
301 |
+
return s + p
|
302 |
+
|
303 |
+
_psi_coeff = [
|
304 |
+
0.083333333333333333333,
|
305 |
+
-0.0083333333333333333333,
|
306 |
+
0.003968253968253968254,
|
307 |
+
-0.0041666666666666666667,
|
308 |
+
0.0075757575757575757576,
|
309 |
+
-0.021092796092796092796,
|
310 |
+
0.083333333333333333333,
|
311 |
+
-0.44325980392156862745,
|
312 |
+
3.0539543302701197438,
|
313 |
+
-26.456212121212121212]
|
314 |
+
|
315 |
+
def _digamma_real(x):
|
316 |
+
_intx = int(x)
|
317 |
+
if _intx == x:
|
318 |
+
if _intx <= 0:
|
319 |
+
raise ZeroDivisionError("polygamma pole")
|
320 |
+
if x < 0.5:
|
321 |
+
x = 1.0-x
|
322 |
+
s = pi*cotpi(x)
|
323 |
+
else:
|
324 |
+
s = 0.0
|
325 |
+
while x < 10.0:
|
326 |
+
s -= 1.0/x
|
327 |
+
x += 1.0
|
328 |
+
x2 = x**-2
|
329 |
+
t = x2
|
330 |
+
for c in _psi_coeff:
|
331 |
+
s -= c*t
|
332 |
+
if t < 1e-20:
|
333 |
+
break
|
334 |
+
t *= x2
|
335 |
+
return s + math_log(x) - 0.5/x
|
336 |
+
|
337 |
+
def _digamma_complex(x):
|
338 |
+
if not x.imag:
|
339 |
+
return complex(_digamma_real(x.real))
|
340 |
+
if x.real < 0.5:
|
341 |
+
x = 1.0-x
|
342 |
+
s = pi*cotpi(x)
|
343 |
+
else:
|
344 |
+
s = 0.0
|
345 |
+
while abs(x) < 10.0:
|
346 |
+
s -= 1.0/x
|
347 |
+
x += 1.0
|
348 |
+
x2 = x**-2
|
349 |
+
t = x2
|
350 |
+
for c in _psi_coeff:
|
351 |
+
s -= c*t
|
352 |
+
if abs(t) < 1e-20:
|
353 |
+
break
|
354 |
+
t *= x2
|
355 |
+
return s + cmath.log(x) - 0.5/x
|
356 |
+
|
357 |
+
digamma = _mathfun_real(_digamma_real, _digamma_complex)
|
358 |
+
|
359 |
+
# TODO: could implement complex erf and erfc here. Need
|
360 |
+
# to find an accurate method (avoiding cancellation)
|
361 |
+
# for approx. 1 < abs(x) < 9.
|
362 |
+
|
363 |
+
_erfc_coeff_P = [
|
364 |
+
1.0000000161203922312,
|
365 |
+
2.1275306946297962644,
|
366 |
+
2.2280433377390253297,
|
367 |
+
1.4695509105618423961,
|
368 |
+
0.66275911699770787537,
|
369 |
+
0.20924776504163751585,
|
370 |
+
0.045459713768411264339,
|
371 |
+
0.0063065951710717791934,
|
372 |
+
0.00044560259661560421715][::-1]
|
373 |
+
|
374 |
+
_erfc_coeff_Q = [
|
375 |
+
1.0000000000000000000,
|
376 |
+
3.2559100272784894318,
|
377 |
+
4.9019435608903239131,
|
378 |
+
4.4971472894498014205,
|
379 |
+
2.7845640601891186528,
|
380 |
+
1.2146026030046904138,
|
381 |
+
0.37647108453729465912,
|
382 |
+
0.080970149639040548613,
|
383 |
+
0.011178148899483545902,
|
384 |
+
0.00078981003831980423513][::-1]
|
385 |
+
|
386 |
+
def _polyval(coeffs, x):
|
387 |
+
p = coeffs[0]
|
388 |
+
for c in coeffs[1:]:
|
389 |
+
p = c + x*p
|
390 |
+
return p
|
391 |
+
|
392 |
+
def _erf_taylor(x):
|
393 |
+
# Taylor series assuming 0 <= x <= 1
|
394 |
+
x2 = x*x
|
395 |
+
s = t = x
|
396 |
+
n = 1
|
397 |
+
while abs(t) > 1e-17:
|
398 |
+
t *= x2/n
|
399 |
+
s -= t/(n+n+1)
|
400 |
+
n += 1
|
401 |
+
t *= x2/n
|
402 |
+
s += t/(n+n+1)
|
403 |
+
n += 1
|
404 |
+
return 1.1283791670955125739*s
|
405 |
+
|
406 |
+
def _erfc_mid(x):
|
407 |
+
# Rational approximation assuming 0 <= x <= 9
|
408 |
+
return exp(-x*x)*_polyval(_erfc_coeff_P,x)/_polyval(_erfc_coeff_Q,x)
|
409 |
+
|
410 |
+
def _erfc_asymp(x):
|
411 |
+
# Asymptotic expansion assuming x >= 9
|
412 |
+
x2 = x*x
|
413 |
+
v = exp(-x2)/x*0.56418958354775628695
|
414 |
+
r = t = 0.5 / x2
|
415 |
+
s = 1.0
|
416 |
+
for n in range(1,22,4):
|
417 |
+
s -= t
|
418 |
+
t *= r * (n+2)
|
419 |
+
s += t
|
420 |
+
t *= r * (n+4)
|
421 |
+
if abs(t) < 1e-17:
|
422 |
+
break
|
423 |
+
return s * v
|
424 |
+
|
425 |
+
def erf(x):
|
426 |
+
"""
|
427 |
+
erf of a real number.
|
428 |
+
"""
|
429 |
+
x = float(x)
|
430 |
+
if x != x:
|
431 |
+
return x
|
432 |
+
if x < 0.0:
|
433 |
+
return -erf(-x)
|
434 |
+
if x >= 1.0:
|
435 |
+
if x >= 6.0:
|
436 |
+
return 1.0
|
437 |
+
return 1.0 - _erfc_mid(x)
|
438 |
+
return _erf_taylor(x)
|
439 |
+
|
440 |
+
def erfc(x):
|
441 |
+
"""
|
442 |
+
erfc of a real number.
|
443 |
+
"""
|
444 |
+
x = float(x)
|
445 |
+
if x != x:
|
446 |
+
return x
|
447 |
+
if x < 0.0:
|
448 |
+
if x < -6.0:
|
449 |
+
return 2.0
|
450 |
+
return 2.0-erfc(-x)
|
451 |
+
if x > 9.0:
|
452 |
+
return _erfc_asymp(x)
|
453 |
+
if x >= 1.0:
|
454 |
+
return _erfc_mid(x)
|
455 |
+
return 1.0 - _erf_taylor(x)
|
456 |
+
|
457 |
+
gauss42 = [\
|
458 |
+
(0.99839961899006235, 0.0041059986046490839),
|
459 |
+
(-0.99839961899006235, 0.0041059986046490839),
|
460 |
+
(0.9915772883408609, 0.009536220301748501),
|
461 |
+
(-0.9915772883408609,0.009536220301748501),
|
462 |
+
(0.97934250806374812, 0.014922443697357493),
|
463 |
+
(-0.97934250806374812, 0.014922443697357493),
|
464 |
+
(0.96175936533820439,0.020227869569052644),
|
465 |
+
(-0.96175936533820439, 0.020227869569052644),
|
466 |
+
(0.93892355735498811, 0.025422959526113047),
|
467 |
+
(-0.93892355735498811,0.025422959526113047),
|
468 |
+
(0.91095972490412735, 0.030479240699603467),
|
469 |
+
(-0.91095972490412735, 0.030479240699603467),
|
470 |
+
(0.87802056981217269,0.03536907109759211),
|
471 |
+
(-0.87802056981217269, 0.03536907109759211),
|
472 |
+
(0.8402859832618168, 0.040065735180692258),
|
473 |
+
(-0.8402859832618168,0.040065735180692258),
|
474 |
+
(0.7979620532554873, 0.044543577771965874),
|
475 |
+
(-0.7979620532554873, 0.044543577771965874),
|
476 |
+
(0.75127993568948048,0.048778140792803244),
|
477 |
+
(-0.75127993568948048, 0.048778140792803244),
|
478 |
+
(0.70049459055617114, 0.052746295699174064),
|
479 |
+
(-0.70049459055617114,0.052746295699174064),
|
480 |
+
(0.64588338886924779, 0.056426369358018376),
|
481 |
+
(-0.64588338886924779, 0.056426369358018376),
|
482 |
+
(0.58774459748510932, 0.059798262227586649),
|
483 |
+
(-0.58774459748510932, 0.059798262227586649),
|
484 |
+
(0.5263957499311922, 0.062843558045002565),
|
485 |
+
(-0.5263957499311922, 0.062843558045002565),
|
486 |
+
(0.46217191207042191, 0.065545624364908975),
|
487 |
+
(-0.46217191207042191, 0.065545624364908975),
|
488 |
+
(0.39542385204297503, 0.067889703376521934),
|
489 |
+
(-0.39542385204297503, 0.067889703376521934),
|
490 |
+
(0.32651612446541151, 0.069862992492594159),
|
491 |
+
(-0.32651612446541151, 0.069862992492594159),
|
492 |
+
(0.25582507934287907, 0.071454714265170971),
|
493 |
+
(-0.25582507934287907, 0.071454714265170971),
|
494 |
+
(0.18373680656485453, 0.072656175243804091),
|
495 |
+
(-0.18373680656485453, 0.072656175243804091),
|
496 |
+
(0.11064502720851986, 0.073460813453467527),
|
497 |
+
(-0.11064502720851986, 0.073460813453467527),
|
498 |
+
(0.036948943165351772, 0.073864234232172879),
|
499 |
+
(-0.036948943165351772, 0.073864234232172879)]
|
500 |
+
|
501 |
+
EI_ASYMP_CONVERGENCE_RADIUS = 40.0
|
502 |
+
|
503 |
+
def ei_asymp(z, _e1=False):
|
504 |
+
r = 1./z
|
505 |
+
s = t = 1.0
|
506 |
+
k = 1
|
507 |
+
while 1:
|
508 |
+
t *= k*r
|
509 |
+
s += t
|
510 |
+
if abs(t) < 1e-16:
|
511 |
+
break
|
512 |
+
k += 1
|
513 |
+
v = s*exp(z)/z
|
514 |
+
if _e1:
|
515 |
+
if type(z) is complex:
|
516 |
+
zreal = z.real
|
517 |
+
zimag = z.imag
|
518 |
+
else:
|
519 |
+
zreal = z
|
520 |
+
zimag = 0.0
|
521 |
+
if zimag == 0.0 and zreal > 0.0:
|
522 |
+
v += pi*1j
|
523 |
+
else:
|
524 |
+
if type(z) is complex:
|
525 |
+
if z.imag > 0:
|
526 |
+
v += pi*1j
|
527 |
+
if z.imag < 0:
|
528 |
+
v -= pi*1j
|
529 |
+
return v
|
530 |
+
|
531 |
+
def ei_taylor(z, _e1=False):
|
532 |
+
s = t = z
|
533 |
+
k = 2
|
534 |
+
while 1:
|
535 |
+
t = t*z/k
|
536 |
+
term = t/k
|
537 |
+
if abs(term) < 1e-17:
|
538 |
+
break
|
539 |
+
s += term
|
540 |
+
k += 1
|
541 |
+
s += euler
|
542 |
+
if _e1:
|
543 |
+
s += log(-z)
|
544 |
+
else:
|
545 |
+
if type(z) is float or z.imag == 0.0:
|
546 |
+
s += math_log(abs(z))
|
547 |
+
else:
|
548 |
+
s += cmath.log(z)
|
549 |
+
return s
|
550 |
+
|
551 |
+
def ei(z, _e1=False):
|
552 |
+
typez = type(z)
|
553 |
+
if typez not in (float, complex):
|
554 |
+
try:
|
555 |
+
z = float(z)
|
556 |
+
typez = float
|
557 |
+
except (TypeError, ValueError):
|
558 |
+
z = complex(z)
|
559 |
+
typez = complex
|
560 |
+
if not z:
|
561 |
+
return -INF
|
562 |
+
absz = abs(z)
|
563 |
+
if absz > EI_ASYMP_CONVERGENCE_RADIUS:
|
564 |
+
return ei_asymp(z, _e1)
|
565 |
+
elif absz <= 2.0 or (typez is float and z > 0.0):
|
566 |
+
return ei_taylor(z, _e1)
|
567 |
+
# Integrate, starting from whichever is smaller of a Taylor
|
568 |
+
# series value or an asymptotic series value
|
569 |
+
if typez is complex and z.real > 0.0:
|
570 |
+
zref = z / absz
|
571 |
+
ref = ei_taylor(zref, _e1)
|
572 |
+
else:
|
573 |
+
zref = EI_ASYMP_CONVERGENCE_RADIUS * z / absz
|
574 |
+
ref = ei_asymp(zref, _e1)
|
575 |
+
C = (zref-z)*0.5
|
576 |
+
D = (zref+z)*0.5
|
577 |
+
s = 0.0
|
578 |
+
if type(z) is complex:
|
579 |
+
_exp = cmath.exp
|
580 |
+
else:
|
581 |
+
_exp = math.exp
|
582 |
+
for x,w in gauss42:
|
583 |
+
t = C*x+D
|
584 |
+
s += w*_exp(t)/t
|
585 |
+
ref -= C*s
|
586 |
+
return ref
|
587 |
+
|
588 |
+
def e1(z):
|
589 |
+
# hack to get consistent signs if the imaginary part if 0
|
590 |
+
# and signed
|
591 |
+
typez = type(z)
|
592 |
+
if type(z) not in (float, complex):
|
593 |
+
try:
|
594 |
+
z = float(z)
|
595 |
+
typez = float
|
596 |
+
except (TypeError, ValueError):
|
597 |
+
z = complex(z)
|
598 |
+
typez = complex
|
599 |
+
if typez is complex and not z.imag:
|
600 |
+
z = complex(z.real, 0.0)
|
601 |
+
# end hack
|
602 |
+
return -ei(-z, _e1=True)
|
603 |
+
|
604 |
+
_zeta_int = [\
|
605 |
+
-0.5,
|
606 |
+
0.0,
|
607 |
+
1.6449340668482264365,1.2020569031595942854,1.0823232337111381915,
|
608 |
+
1.0369277551433699263,1.0173430619844491397,1.0083492773819228268,
|
609 |
+
1.0040773561979443394,1.0020083928260822144,1.0009945751278180853,
|
610 |
+
1.0004941886041194646,1.0002460865533080483,1.0001227133475784891,
|
611 |
+
1.0000612481350587048,1.0000305882363070205,1.0000152822594086519,
|
612 |
+
1.0000076371976378998,1.0000038172932649998,1.0000019082127165539,
|
613 |
+
1.0000009539620338728,1.0000004769329867878,1.0000002384505027277,
|
614 |
+
1.0000001192199259653,1.0000000596081890513,1.0000000298035035147,
|
615 |
+
1.0000000149015548284]
|
616 |
+
|
617 |
+
_zeta_P = [-3.50000000087575873, -0.701274355654678147,
|
618 |
+
-0.0672313458590012612, -0.00398731457954257841,
|
619 |
+
-0.000160948723019303141, -4.67633010038383371e-6,
|
620 |
+
-1.02078104417700585e-7, -1.68030037095896287e-9,
|
621 |
+
-1.85231868742346722e-11][::-1]
|
622 |
+
|
623 |
+
_zeta_Q = [1.00000000000000000, -0.936552848762465319,
|
624 |
+
-0.0588835413263763741, -0.00441498861482948666,
|
625 |
+
-0.000143416758067432622, -5.10691659585090782e-6,
|
626 |
+
-9.58813053268913799e-8, -1.72963791443181972e-9,
|
627 |
+
-1.83527919681474132e-11][::-1]
|
628 |
+
|
629 |
+
_zeta_1 = [3.03768838606128127e-10, -1.21924525236601262e-8,
|
630 |
+
2.01201845887608893e-7, -1.53917240683468381e-6,
|
631 |
+
-5.09890411005967954e-7, 0.000122464707271619326,
|
632 |
+
-0.000905721539353130232, -0.00239315326074843037,
|
633 |
+
0.084239750013159168, 0.418938517907442414, 0.500000001921884009]
|
634 |
+
|
635 |
+
_zeta_0 = [-3.46092485016748794e-10, -6.42610089468292485e-9,
|
636 |
+
1.76409071536679773e-7, -1.47141263991560698e-6, -6.38880222546167613e-7,
|
637 |
+
0.000122641099800668209, -0.000905894913516772796, -0.00239303348507992713,
|
638 |
+
0.0842396947501199816, 0.418938533204660256, 0.500000000000000052]
|
639 |
+
|
640 |
+
def zeta(s):
|
641 |
+
"""
|
642 |
+
Riemann zeta function, real argument
|
643 |
+
"""
|
644 |
+
if not isinstance(s, (float, int)):
|
645 |
+
try:
|
646 |
+
s = float(s)
|
647 |
+
except (ValueError, TypeError):
|
648 |
+
try:
|
649 |
+
s = complex(s)
|
650 |
+
if not s.imag:
|
651 |
+
return complex(zeta(s.real))
|
652 |
+
except (ValueError, TypeError):
|
653 |
+
pass
|
654 |
+
raise NotImplementedError
|
655 |
+
if s == 1:
|
656 |
+
raise ValueError("zeta(1) pole")
|
657 |
+
if s >= 27:
|
658 |
+
return 1.0 + 2.0**(-s) + 3.0**(-s)
|
659 |
+
n = int(s)
|
660 |
+
if n == s:
|
661 |
+
if n >= 0:
|
662 |
+
return _zeta_int[n]
|
663 |
+
if not (n % 2):
|
664 |
+
return 0.0
|
665 |
+
if s <= 0.0:
|
666 |
+
return 2.**s*pi**(s-1)*_sinpi_real(0.5*s)*_gamma_real(1-s)*zeta(1-s)
|
667 |
+
if s <= 2.0:
|
668 |
+
if s <= 1.0:
|
669 |
+
return _polyval(_zeta_0,s)/(s-1)
|
670 |
+
return _polyval(_zeta_1,s)/(s-1)
|
671 |
+
z = _polyval(_zeta_P,s) / _polyval(_zeta_Q,s)
|
672 |
+
return 1.0 + 2.0**(-s) + 3.0**(-s) + 4.0**(-s)*z
|
env-llmeval/lib/python3.10/site-packages/mpmath/matrices/__init__.py
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
from . import eigen # to set methods
|
2 |
+
from . import eigen_symmetric # to set methods
|
env-llmeval/lib/python3.10/site-packages/mpmath/matrices/eigen_symmetric.py
ADDED
@@ -0,0 +1,1807 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/python
|
2 |
+
# -*- coding: utf-8 -*-
|
3 |
+
|
4 |
+
##################################################################################################
|
5 |
+
# module for the symmetric eigenvalue problem
|
6 |
+
# Copyright 2013 Timo Hartmann (thartmann15 at gmail.com)
|
7 |
+
#
|
8 |
+
# todo:
|
9 |
+
# - implement balancing
|
10 |
+
#
|
11 |
+
##################################################################################################
|
12 |
+
|
13 |
+
"""
|
14 |
+
The symmetric eigenvalue problem.
|
15 |
+
---------------------------------
|
16 |
+
|
17 |
+
This file contains routines for the symmetric eigenvalue problem.
|
18 |
+
|
19 |
+
high level routines:
|
20 |
+
|
21 |
+
eigsy : real symmetric (ordinary) eigenvalue problem
|
22 |
+
eighe : complex hermitian (ordinary) eigenvalue problem
|
23 |
+
eigh : unified interface for eigsy and eighe
|
24 |
+
svd_r : singular value decomposition for real matrices
|
25 |
+
svd_c : singular value decomposition for complex matrices
|
26 |
+
svd : unified interface for svd_r and svd_c
|
27 |
+
|
28 |
+
|
29 |
+
low level routines:
|
30 |
+
|
31 |
+
r_sy_tridiag : reduction of real symmetric matrix to real symmetric tridiagonal matrix
|
32 |
+
c_he_tridiag_0 : reduction of complex hermitian matrix to real symmetric tridiagonal matrix
|
33 |
+
c_he_tridiag_1 : auxiliary routine to c_he_tridiag_0
|
34 |
+
c_he_tridiag_2 : auxiliary routine to c_he_tridiag_0
|
35 |
+
tridiag_eigen : solves the real symmetric tridiagonal matrix eigenvalue problem
|
36 |
+
svd_r_raw : raw singular value decomposition for real matrices
|
37 |
+
svd_c_raw : raw singular value decomposition for complex matrices
|
38 |
+
"""
|
39 |
+
|
40 |
+
from ..libmp.backend import xrange
|
41 |
+
from .eigen import defun
|
42 |
+
|
43 |
+
|
44 |
+
def r_sy_tridiag(ctx, A, D, E, calc_ev = True):
|
45 |
+
"""
|
46 |
+
This routine transforms a real symmetric matrix A to a real symmetric
|
47 |
+
tridiagonal matrix T using an orthogonal similarity transformation:
|
48 |
+
Q' * A * Q = T (here ' denotes the matrix transpose).
|
49 |
+
The orthogonal matrix Q is build up from Householder reflectors.
|
50 |
+
|
51 |
+
parameters:
|
52 |
+
A (input/output) On input, A contains the real symmetric matrix of
|
53 |
+
dimension (n,n). On output, if calc_ev is true, A contains the
|
54 |
+
orthogonal matrix Q, otherwise A is destroyed.
|
55 |
+
|
56 |
+
D (output) real array of length n, contains the diagonal elements
|
57 |
+
of the tridiagonal matrix
|
58 |
+
|
59 |
+
E (output) real array of length n, contains the offdiagonal elements
|
60 |
+
of the tridiagonal matrix in E[0:(n-1)] where is the dimension of
|
61 |
+
the matrix A. E[n-1] is undefined.
|
62 |
+
|
63 |
+
calc_ev (input) If calc_ev is true, this routine explicitly calculates the
|
64 |
+
orthogonal matrix Q which is then returned in A. If calc_ev is
|
65 |
+
false, Q is not explicitly calculated resulting in a shorter run time.
|
66 |
+
|
67 |
+
This routine is a python translation of the fortran routine tred2.f in the
|
68 |
+
software library EISPACK (see netlib.org) which itself is based on the algol
|
69 |
+
procedure tred2 described in:
|
70 |
+
- Num. Math. 11, p.181-195 (1968) by Martin, Reinsch and Wilkonson
|
71 |
+
- Handbook for auto. comp., Vol II, Linear Algebra, p.212-226 (1971)
|
72 |
+
|
73 |
+
For a good introduction to Householder reflections, see also
|
74 |
+
Stoer, Bulirsch - Introduction to Numerical Analysis.
|
75 |
+
"""
|
76 |
+
|
77 |
+
# note : the vector v of the i-th houshoulder reflector is stored in a[(i+1):,i]
|
78 |
+
# whereas v/<v,v> is stored in a[i,(i+1):]
|
79 |
+
|
80 |
+
n = A.rows
|
81 |
+
for i in xrange(n - 1, 0, -1):
|
82 |
+
# scale the vector
|
83 |
+
|
84 |
+
scale = 0
|
85 |
+
for k in xrange(0, i):
|
86 |
+
scale += abs(A[k,i])
|
87 |
+
|
88 |
+
scale_inv = 0
|
89 |
+
if scale != 0:
|
90 |
+
scale_inv = 1/scale
|
91 |
+
|
92 |
+
# sadly there are floating point numbers not equal to zero whose reciprocal is infinity
|
93 |
+
|
94 |
+
if i == 1 or scale == 0 or ctx.isinf(scale_inv):
|
95 |
+
E[i] = A[i-1,i] # nothing to do
|
96 |
+
D[i] = 0
|
97 |
+
continue
|
98 |
+
|
99 |
+
# calculate parameters for housholder transformation
|
100 |
+
|
101 |
+
H = 0
|
102 |
+
for k in xrange(0, i):
|
103 |
+
A[k,i] *= scale_inv
|
104 |
+
H += A[k,i] * A[k,i]
|
105 |
+
|
106 |
+
F = A[i-1,i]
|
107 |
+
G = ctx.sqrt(H)
|
108 |
+
if F > 0:
|
109 |
+
G = -G
|
110 |
+
E[i] = scale * G
|
111 |
+
H -= F * G
|
112 |
+
A[i-1,i] = F - G
|
113 |
+
F = 0
|
114 |
+
|
115 |
+
# apply housholder transformation
|
116 |
+
|
117 |
+
for j in xrange(0, i):
|
118 |
+
if calc_ev:
|
119 |
+
A[i,j] = A[j,i] / H
|
120 |
+
|
121 |
+
G = 0 # calculate A*U
|
122 |
+
for k in xrange(0, j + 1):
|
123 |
+
G += A[k,j] * A[k,i]
|
124 |
+
for k in xrange(j + 1, i):
|
125 |
+
G += A[j,k] * A[k,i]
|
126 |
+
|
127 |
+
E[j] = G / H # calculate P
|
128 |
+
F += E[j] * A[j,i]
|
129 |
+
|
130 |
+
HH = F / (2 * H)
|
131 |
+
|
132 |
+
for j in xrange(0, i): # calculate reduced A
|
133 |
+
F = A[j,i]
|
134 |
+
G = E[j] - HH * F # calculate Q
|
135 |
+
E[j] = G
|
136 |
+
|
137 |
+
for k in xrange(0, j + 1):
|
138 |
+
A[k,j] -= F * E[k] + G * A[k,i]
|
139 |
+
|
140 |
+
D[i] = H
|
141 |
+
|
142 |
+
for i in xrange(1, n): # better for compatibility
|
143 |
+
E[i-1] = E[i]
|
144 |
+
E[n-1] = 0
|
145 |
+
|
146 |
+
if calc_ev:
|
147 |
+
D[0] = 0
|
148 |
+
for i in xrange(0, n):
|
149 |
+
if D[i] != 0:
|
150 |
+
for j in xrange(0, i): # accumulate transformation matrices
|
151 |
+
G = 0
|
152 |
+
for k in xrange(0, i):
|
153 |
+
G += A[i,k] * A[k,j]
|
154 |
+
for k in xrange(0, i):
|
155 |
+
A[k,j] -= G * A[k,i]
|
156 |
+
|
157 |
+
D[i] = A[i,i]
|
158 |
+
A[i,i] = 1
|
159 |
+
|
160 |
+
for j in xrange(0, i):
|
161 |
+
A[j,i] = A[i,j] = 0
|
162 |
+
else:
|
163 |
+
for i in xrange(0, n):
|
164 |
+
D[i] = A[i,i]
|
165 |
+
|
166 |
+
|
167 |
+
|
168 |
+
|
169 |
+
|
170 |
+
def c_he_tridiag_0(ctx, A, D, E, T):
|
171 |
+
"""
|
172 |
+
This routine transforms a complex hermitian matrix A to a real symmetric
|
173 |
+
tridiagonal matrix T using an unitary similarity transformation:
|
174 |
+
Q' * A * Q = T (here ' denotes the hermitian matrix transpose,
|
175 |
+
i.e. transposition und conjugation).
|
176 |
+
The unitary matrix Q is build up from Householder reflectors and
|
177 |
+
an unitary diagonal matrix.
|
178 |
+
|
179 |
+
parameters:
|
180 |
+
A (input/output) On input, A contains the complex hermitian matrix
|
181 |
+
of dimension (n,n). On output, A contains the unitary matrix Q
|
182 |
+
in compressed form.
|
183 |
+
|
184 |
+
D (output) real array of length n, contains the diagonal elements
|
185 |
+
of the tridiagonal matrix.
|
186 |
+
|
187 |
+
E (output) real array of length n, contains the offdiagonal elements
|
188 |
+
of the tridiagonal matrix in E[0:(n-1)] where is the dimension of
|
189 |
+
the matrix A. E[n-1] is undefined.
|
190 |
+
|
191 |
+
T (output) complex array of length n, contains a unitary diagonal
|
192 |
+
matrix.
|
193 |
+
|
194 |
+
This routine is a python translation (in slightly modified form) of the fortran
|
195 |
+
routine htridi.f in the software library EISPACK (see netlib.org) which itself
|
196 |
+
is a complex version of the algol procedure tred1 described in:
|
197 |
+
- Num. Math. 11, p.181-195 (1968) by Martin, Reinsch and Wilkonson
|
198 |
+
- Handbook for auto. comp., Vol II, Linear Algebra, p.212-226 (1971)
|
199 |
+
|
200 |
+
For a good introduction to Householder reflections, see also
|
201 |
+
Stoer, Bulirsch - Introduction to Numerical Analysis.
|
202 |
+
"""
|
203 |
+
|
204 |
+
n = A.rows
|
205 |
+
T[n-1] = 1
|
206 |
+
for i in xrange(n - 1, 0, -1):
|
207 |
+
|
208 |
+
# scale the vector
|
209 |
+
|
210 |
+
scale = 0
|
211 |
+
for k in xrange(0, i):
|
212 |
+
scale += abs(ctx.re(A[k,i])) + abs(ctx.im(A[k,i]))
|
213 |
+
|
214 |
+
scale_inv = 0
|
215 |
+
if scale != 0:
|
216 |
+
scale_inv = 1 / scale
|
217 |
+
|
218 |
+
# sadly there are floating point numbers not equal to zero whose reciprocal is infinity
|
219 |
+
|
220 |
+
if scale == 0 or ctx.isinf(scale_inv):
|
221 |
+
E[i] = 0
|
222 |
+
D[i] = 0
|
223 |
+
T[i-1] = 1
|
224 |
+
continue
|
225 |
+
|
226 |
+
if i == 1:
|
227 |
+
F = A[i-1,i]
|
228 |
+
f = abs(F)
|
229 |
+
E[i] = f
|
230 |
+
D[i] = 0
|
231 |
+
if f != 0:
|
232 |
+
T[i-1] = T[i] * F / f
|
233 |
+
else:
|
234 |
+
T[i-1] = T[i]
|
235 |
+
continue
|
236 |
+
|
237 |
+
# calculate parameters for housholder transformation
|
238 |
+
|
239 |
+
H = 0
|
240 |
+
for k in xrange(0, i):
|
241 |
+
A[k,i] *= scale_inv
|
242 |
+
rr = ctx.re(A[k,i])
|
243 |
+
ii = ctx.im(A[k,i])
|
244 |
+
H += rr * rr + ii * ii
|
245 |
+
|
246 |
+
F = A[i-1,i]
|
247 |
+
f = abs(F)
|
248 |
+
G = ctx.sqrt(H)
|
249 |
+
H += G * f
|
250 |
+
E[i] = scale * G
|
251 |
+
if f != 0:
|
252 |
+
F = F / f
|
253 |
+
TZ = - T[i] * F # T[i-1]=-T[i]*F, but we need T[i-1] as temporary storage
|
254 |
+
G *= F
|
255 |
+
else:
|
256 |
+
TZ = -T[i] # T[i-1]=-T[i]
|
257 |
+
A[i-1,i] += G
|
258 |
+
F = 0
|
259 |
+
|
260 |
+
# apply housholder transformation
|
261 |
+
|
262 |
+
for j in xrange(0, i):
|
263 |
+
A[i,j] = A[j,i] / H
|
264 |
+
|
265 |
+
G = 0 # calculate A*U
|
266 |
+
for k in xrange(0, j + 1):
|
267 |
+
G += ctx.conj(A[k,j]) * A[k,i]
|
268 |
+
for k in xrange(j + 1, i):
|
269 |
+
G += A[j,k] * A[k,i]
|
270 |
+
|
271 |
+
T[j] = G / H # calculate P
|
272 |
+
F += ctx.conj(T[j]) * A[j,i]
|
273 |
+
|
274 |
+
HH = F / (2 * H)
|
275 |
+
|
276 |
+
for j in xrange(0, i): # calculate reduced A
|
277 |
+
F = A[j,i]
|
278 |
+
G = T[j] - HH * F # calculate Q
|
279 |
+
T[j] = G
|
280 |
+
|
281 |
+
for k in xrange(0, j + 1):
|
282 |
+
A[k,j] -= ctx.conj(F) * T[k] + ctx.conj(G) * A[k,i]
|
283 |
+
# as we use the lower left part for storage
|
284 |
+
# we have to use the transpose of the normal formula
|
285 |
+
|
286 |
+
T[i-1] = TZ
|
287 |
+
D[i] = H
|
288 |
+
|
289 |
+
for i in xrange(1, n): # better for compatibility
|
290 |
+
E[i-1] = E[i]
|
291 |
+
E[n-1] = 0
|
292 |
+
|
293 |
+
D[0] = 0
|
294 |
+
for i in xrange(0, n):
|
295 |
+
zw = D[i]
|
296 |
+
D[i] = ctx.re(A[i,i])
|
297 |
+
A[i,i] = zw
|
298 |
+
|
299 |
+
|
300 |
+
|
301 |
+
|
302 |
+
|
303 |
+
|
304 |
+
|
305 |
+
def c_he_tridiag_1(ctx, A, T):
|
306 |
+
"""
|
307 |
+
This routine forms the unitary matrix Q described in c_he_tridiag_0.
|
308 |
+
|
309 |
+
parameters:
|
310 |
+
A (input/output) On input, A is the same matrix as delivered by
|
311 |
+
c_he_tridiag_0. On output, A is set to Q.
|
312 |
+
|
313 |
+
T (input) On input, T is the same array as delivered by c_he_tridiag_0.
|
314 |
+
|
315 |
+
"""
|
316 |
+
|
317 |
+
n = A.rows
|
318 |
+
|
319 |
+
for i in xrange(0, n):
|
320 |
+
if A[i,i] != 0:
|
321 |
+
for j in xrange(0, i):
|
322 |
+
G = 0
|
323 |
+
for k in xrange(0, i):
|
324 |
+
G += ctx.conj(A[i,k]) * A[k,j]
|
325 |
+
for k in xrange(0, i):
|
326 |
+
A[k,j] -= G * A[k,i]
|
327 |
+
|
328 |
+
A[i,i] = 1
|
329 |
+
|
330 |
+
for j in xrange(0, i):
|
331 |
+
A[j,i] = A[i,j] = 0
|
332 |
+
|
333 |
+
for i in xrange(0, n):
|
334 |
+
for k in xrange(0, n):
|
335 |
+
A[i,k] *= T[k]
|
336 |
+
|
337 |
+
|
338 |
+
|
339 |
+
|
340 |
+
def c_he_tridiag_2(ctx, A, T, B):
|
341 |
+
"""
|
342 |
+
This routine applied the unitary matrix Q described in c_he_tridiag_0
|
343 |
+
onto the the matrix B, i.e. it forms Q*B.
|
344 |
+
|
345 |
+
parameters:
|
346 |
+
A (input) On input, A is the same matrix as delivered by c_he_tridiag_0.
|
347 |
+
|
348 |
+
T (input) On input, T is the same array as delivered by c_he_tridiag_0.
|
349 |
+
|
350 |
+
B (input/output) On input, B is a complex matrix. On output B is replaced
|
351 |
+
by Q*B.
|
352 |
+
|
353 |
+
This routine is a python translation of the fortran routine htribk.f in the
|
354 |
+
software library EISPACK (see netlib.org). See c_he_tridiag_0 for more
|
355 |
+
references.
|
356 |
+
"""
|
357 |
+
|
358 |
+
n = A.rows
|
359 |
+
|
360 |
+
for i in xrange(0, n):
|
361 |
+
for k in xrange(0, n):
|
362 |
+
B[k,i] *= T[k]
|
363 |
+
|
364 |
+
for i in xrange(0, n):
|
365 |
+
if A[i,i] != 0:
|
366 |
+
for j in xrange(0, n):
|
367 |
+
G = 0
|
368 |
+
for k in xrange(0, i):
|
369 |
+
G += ctx.conj(A[i,k]) * B[k,j]
|
370 |
+
for k in xrange(0, i):
|
371 |
+
B[k,j] -= G * A[k,i]
|
372 |
+
|
373 |
+
|
374 |
+
|
375 |
+
|
376 |
+
|
377 |
+
def tridiag_eigen(ctx, d, e, z = False):
|
378 |
+
"""
|
379 |
+
This subroutine find the eigenvalues and the first components of the
|
380 |
+
eigenvectors of a real symmetric tridiagonal matrix using the implicit
|
381 |
+
QL method.
|
382 |
+
|
383 |
+
parameters:
|
384 |
+
|
385 |
+
d (input/output) real array of length n. on input, d contains the diagonal
|
386 |
+
elements of the input matrix. on output, d contains the eigenvalues in
|
387 |
+
ascending order.
|
388 |
+
|
389 |
+
e (input) real array of length n. on input, e contains the offdiagonal
|
390 |
+
elements of the input matrix in e[0:(n-1)]. On output, e has been
|
391 |
+
destroyed.
|
392 |
+
|
393 |
+
z (input/output) If z is equal to False, no eigenvectors will be computed.
|
394 |
+
Otherwise on input z should have the format z[0:m,0:n] (i.e. a real or
|
395 |
+
complex matrix of dimension (m,n) ). On output this matrix will be
|
396 |
+
multiplied by the matrix of the eigenvectors (i.e. the columns of this
|
397 |
+
matrix are the eigenvectors): z --> z*EV
|
398 |
+
That means if z[i,j]={1 if j==j; 0 otherwise} on input, then on output
|
399 |
+
z will contain the first m components of the eigenvectors. That means
|
400 |
+
if m is equal to n, the i-th eigenvector will be z[:,i].
|
401 |
+
|
402 |
+
This routine is a python translation (in slightly modified form) of the
|
403 |
+
fortran routine imtql2.f in the software library EISPACK (see netlib.org)
|
404 |
+
which itself is based on the algol procudure imtql2 desribed in:
|
405 |
+
- num. math. 12, p. 377-383(1968) by matrin and wilkinson
|
406 |
+
- modified in num. math. 15, p. 450(1970) by dubrulle
|
407 |
+
- handbook for auto. comp., vol. II-linear algebra, p. 241-248 (1971)
|
408 |
+
See also the routine gaussq.f in netlog.org or acm algorithm 726.
|
409 |
+
"""
|
410 |
+
|
411 |
+
n = len(d)
|
412 |
+
e[n-1] = 0
|
413 |
+
iterlim = 2 * ctx.dps
|
414 |
+
|
415 |
+
for l in xrange(n):
|
416 |
+
j = 0
|
417 |
+
while 1:
|
418 |
+
m = l
|
419 |
+
while 1:
|
420 |
+
# look for a small subdiagonal element
|
421 |
+
if m + 1 == n:
|
422 |
+
break
|
423 |
+
if abs(e[m]) <= ctx.eps * (abs(d[m]) + abs(d[m + 1])):
|
424 |
+
break
|
425 |
+
m = m + 1
|
426 |
+
if m == l:
|
427 |
+
break
|
428 |
+
|
429 |
+
if j >= iterlim:
|
430 |
+
raise RuntimeError("tridiag_eigen: no convergence to an eigenvalue after %d iterations" % iterlim)
|
431 |
+
|
432 |
+
j += 1
|
433 |
+
|
434 |
+
# form shift
|
435 |
+
|
436 |
+
p = d[l]
|
437 |
+
g = (d[l + 1] - p) / (2 * e[l])
|
438 |
+
r = ctx.hypot(g, 1)
|
439 |
+
|
440 |
+
if g < 0:
|
441 |
+
s = g - r
|
442 |
+
else:
|
443 |
+
s = g + r
|
444 |
+
|
445 |
+
g = d[m] - p + e[l] / s
|
446 |
+
|
447 |
+
s, c, p = 1, 1, 0
|
448 |
+
|
449 |
+
for i in xrange(m - 1, l - 1, -1):
|
450 |
+
f = s * e[i]
|
451 |
+
b = c * e[i]
|
452 |
+
if abs(f) > abs(g): # this here is a slight improvement also used in gaussq.f or acm algorithm 726.
|
453 |
+
c = g / f
|
454 |
+
r = ctx.hypot(c, 1)
|
455 |
+
e[i + 1] = f * r
|
456 |
+
s = 1 / r
|
457 |
+
c = c * s
|
458 |
+
else:
|
459 |
+
s = f / g
|
460 |
+
r = ctx.hypot(s, 1)
|
461 |
+
e[i + 1] = g * r
|
462 |
+
c = 1 / r
|
463 |
+
s = s * c
|
464 |
+
g = d[i + 1] - p
|
465 |
+
r = (d[i] - g) * s + 2 * c * b
|
466 |
+
p = s * r
|
467 |
+
d[i + 1] = g + p
|
468 |
+
g = c * r - b
|
469 |
+
|
470 |
+
if not isinstance(z, bool):
|
471 |
+
# calculate eigenvectors
|
472 |
+
for w in xrange(z.rows):
|
473 |
+
f = z[w,i+1]
|
474 |
+
z[w,i+1] = s * z[w,i] + c * f
|
475 |
+
z[w,i ] = c * z[w,i] - s * f
|
476 |
+
|
477 |
+
d[l] = d[l] - p
|
478 |
+
e[l] = g
|
479 |
+
e[m] = 0
|
480 |
+
|
481 |
+
for ii in xrange(1, n):
|
482 |
+
# sort eigenvalues and eigenvectors (bubble-sort)
|
483 |
+
i = ii - 1
|
484 |
+
k = i
|
485 |
+
p = d[i]
|
486 |
+
for j in xrange(ii, n):
|
487 |
+
if d[j] >= p:
|
488 |
+
continue
|
489 |
+
k = j
|
490 |
+
p = d[k]
|
491 |
+
if k == i:
|
492 |
+
continue
|
493 |
+
d[k] = d[i]
|
494 |
+
d[i] = p
|
495 |
+
|
496 |
+
if not isinstance(z, bool):
|
497 |
+
for w in xrange(z.rows):
|
498 |
+
p = z[w,i]
|
499 |
+
z[w,i] = z[w,k]
|
500 |
+
z[w,k] = p
|
501 |
+
|
502 |
+
########################################################################################
|
503 |
+
|
504 |
+
@defun
|
505 |
+
def eigsy(ctx, A, eigvals_only = False, overwrite_a = False):
|
506 |
+
"""
|
507 |
+
This routine solves the (ordinary) eigenvalue problem for a real symmetric
|
508 |
+
square matrix A. Given A, an orthogonal matrix Q is calculated which
|
509 |
+
diagonalizes A:
|
510 |
+
|
511 |
+
Q' A Q = diag(E) and Q Q' = Q' Q = 1
|
512 |
+
|
513 |
+
Here diag(E) is a diagonal matrix whose diagonal is E.
|
514 |
+
' denotes the transpose.
|
515 |
+
|
516 |
+
The columns of Q are the eigenvectors of A and E contains the eigenvalues:
|
517 |
+
|
518 |
+
A Q[:,i] = E[i] Q[:,i]
|
519 |
+
|
520 |
+
|
521 |
+
input:
|
522 |
+
|
523 |
+
A: real matrix of format (n,n) which is symmetric
|
524 |
+
(i.e. A=A' or A[i,j]=A[j,i])
|
525 |
+
|
526 |
+
eigvals_only: if true, calculates only the eigenvalues E.
|
527 |
+
if false, calculates both eigenvectors and eigenvalues.
|
528 |
+
|
529 |
+
overwrite_a: if true, allows modification of A which may improve
|
530 |
+
performance. if false, A is not modified.
|
531 |
+
|
532 |
+
output:
|
533 |
+
|
534 |
+
E: vector of format (n). contains the eigenvalues of A in ascending order.
|
535 |
+
|
536 |
+
Q: orthogonal matrix of format (n,n). contains the eigenvectors
|
537 |
+
of A as columns.
|
538 |
+
|
539 |
+
return value:
|
540 |
+
|
541 |
+
E if eigvals_only is true
|
542 |
+
(E, Q) if eigvals_only is false
|
543 |
+
|
544 |
+
example:
|
545 |
+
>>> from mpmath import mp
|
546 |
+
>>> A = mp.matrix([[3, 2], [2, 0]])
|
547 |
+
>>> E = mp.eigsy(A, eigvals_only = True)
|
548 |
+
>>> print(E)
|
549 |
+
[-1.0]
|
550 |
+
[ 4.0]
|
551 |
+
|
552 |
+
>>> A = mp.matrix([[1, 2], [2, 3]])
|
553 |
+
>>> E, Q = mp.eigsy(A)
|
554 |
+
>>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0]))
|
555 |
+
[0.0]
|
556 |
+
[0.0]
|
557 |
+
|
558 |
+
see also: eighe, eigh, eig
|
559 |
+
"""
|
560 |
+
|
561 |
+
if not overwrite_a:
|
562 |
+
A = A.copy()
|
563 |
+
|
564 |
+
d = ctx.zeros(A.rows, 1)
|
565 |
+
e = ctx.zeros(A.rows, 1)
|
566 |
+
|
567 |
+
if eigvals_only:
|
568 |
+
r_sy_tridiag(ctx, A, d, e, calc_ev = False)
|
569 |
+
tridiag_eigen(ctx, d, e, False)
|
570 |
+
return d
|
571 |
+
else:
|
572 |
+
r_sy_tridiag(ctx, A, d, e, calc_ev = True)
|
573 |
+
tridiag_eigen(ctx, d, e, A)
|
574 |
+
return (d, A)
|
575 |
+
|
576 |
+
|
577 |
+
@defun
|
578 |
+
def eighe(ctx, A, eigvals_only = False, overwrite_a = False):
|
579 |
+
"""
|
580 |
+
This routine solves the (ordinary) eigenvalue problem for a complex
|
581 |
+
hermitian square matrix A. Given A, an unitary matrix Q is calculated which
|
582 |
+
diagonalizes A:
|
583 |
+
|
584 |
+
Q' A Q = diag(E) and Q Q' = Q' Q = 1
|
585 |
+
|
586 |
+
Here diag(E) a is diagonal matrix whose diagonal is E.
|
587 |
+
' denotes the hermitian transpose (i.e. ordinary transposition and
|
588 |
+
complex conjugation).
|
589 |
+
|
590 |
+
The columns of Q are the eigenvectors of A and E contains the eigenvalues:
|
591 |
+
|
592 |
+
A Q[:,i] = E[i] Q[:,i]
|
593 |
+
|
594 |
+
|
595 |
+
input:
|
596 |
+
|
597 |
+
A: complex matrix of format (n,n) which is hermitian
|
598 |
+
(i.e. A=A' or A[i,j]=conj(A[j,i]))
|
599 |
+
|
600 |
+
eigvals_only: if true, calculates only the eigenvalues E.
|
601 |
+
if false, calculates both eigenvectors and eigenvalues.
|
602 |
+
|
603 |
+
overwrite_a: if true, allows modification of A which may improve
|
604 |
+
performance. if false, A is not modified.
|
605 |
+
|
606 |
+
output:
|
607 |
+
|
608 |
+
E: vector of format (n). contains the eigenvalues of A in ascending order.
|
609 |
+
|
610 |
+
Q: unitary matrix of format (n,n). contains the eigenvectors
|
611 |
+
of A as columns.
|
612 |
+
|
613 |
+
return value:
|
614 |
+
|
615 |
+
E if eigvals_only is true
|
616 |
+
(E, Q) if eigvals_only is false
|
617 |
+
|
618 |
+
example:
|
619 |
+
>>> from mpmath import mp
|
620 |
+
>>> A = mp.matrix([[1, -3 - 1j], [-3 + 1j, -2]])
|
621 |
+
>>> E = mp.eighe(A, eigvals_only = True)
|
622 |
+
>>> print(E)
|
623 |
+
[-4.0]
|
624 |
+
[ 3.0]
|
625 |
+
|
626 |
+
>>> A = mp.matrix([[1, 2 + 5j], [2 - 5j, 3]])
|
627 |
+
>>> E, Q = mp.eighe(A)
|
628 |
+
>>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0]))
|
629 |
+
[0.0]
|
630 |
+
[0.0]
|
631 |
+
|
632 |
+
see also: eigsy, eigh, eig
|
633 |
+
"""
|
634 |
+
|
635 |
+
if not overwrite_a:
|
636 |
+
A = A.copy()
|
637 |
+
|
638 |
+
d = ctx.zeros(A.rows, 1)
|
639 |
+
e = ctx.zeros(A.rows, 1)
|
640 |
+
t = ctx.zeros(A.rows, 1)
|
641 |
+
|
642 |
+
if eigvals_only:
|
643 |
+
c_he_tridiag_0(ctx, A, d, e, t)
|
644 |
+
tridiag_eigen(ctx, d, e, False)
|
645 |
+
return d
|
646 |
+
else:
|
647 |
+
c_he_tridiag_0(ctx, A, d, e, t)
|
648 |
+
B = ctx.eye(A.rows)
|
649 |
+
tridiag_eigen(ctx, d, e, B)
|
650 |
+
c_he_tridiag_2(ctx, A, t, B)
|
651 |
+
return (d, B)
|
652 |
+
|
653 |
+
@defun
|
654 |
+
def eigh(ctx, A, eigvals_only = False, overwrite_a = False):
|
655 |
+
"""
|
656 |
+
"eigh" is a unified interface for "eigsy" and "eighe". Depending on
|
657 |
+
whether A is real or complex the appropriate function is called.
|
658 |
+
|
659 |
+
This routine solves the (ordinary) eigenvalue problem for a real symmetric
|
660 |
+
or complex hermitian square matrix A. Given A, an orthogonal (A real) or
|
661 |
+
unitary (A complex) matrix Q is calculated which diagonalizes A:
|
662 |
+
|
663 |
+
Q' A Q = diag(E) and Q Q' = Q' Q = 1
|
664 |
+
|
665 |
+
Here diag(E) a is diagonal matrix whose diagonal is E.
|
666 |
+
' denotes the hermitian transpose (i.e. ordinary transposition and
|
667 |
+
complex conjugation).
|
668 |
+
|
669 |
+
The columns of Q are the eigenvectors of A and E contains the eigenvalues:
|
670 |
+
|
671 |
+
A Q[:,i] = E[i] Q[:,i]
|
672 |
+
|
673 |
+
input:
|
674 |
+
|
675 |
+
A: a real or complex square matrix of format (n,n) which is symmetric
|
676 |
+
(i.e. A[i,j]=A[j,i]) or hermitian (i.e. A[i,j]=conj(A[j,i])).
|
677 |
+
|
678 |
+
eigvals_only: if true, calculates only the eigenvalues E.
|
679 |
+
if false, calculates both eigenvectors and eigenvalues.
|
680 |
+
|
681 |
+
overwrite_a: if true, allows modification of A which may improve
|
682 |
+
performance. if false, A is not modified.
|
683 |
+
|
684 |
+
output:
|
685 |
+
|
686 |
+
E: vector of format (n). contains the eigenvalues of A in ascending order.
|
687 |
+
|
688 |
+
Q: an orthogonal or unitary matrix of format (n,n). contains the
|
689 |
+
eigenvectors of A as columns.
|
690 |
+
|
691 |
+
return value:
|
692 |
+
|
693 |
+
E if eigvals_only is true
|
694 |
+
(E, Q) if eigvals_only is false
|
695 |
+
|
696 |
+
example:
|
697 |
+
>>> from mpmath import mp
|
698 |
+
>>> A = mp.matrix([[3, 2], [2, 0]])
|
699 |
+
>>> E = mp.eigh(A, eigvals_only = True)
|
700 |
+
>>> print(E)
|
701 |
+
[-1.0]
|
702 |
+
[ 4.0]
|
703 |
+
|
704 |
+
>>> A = mp.matrix([[1, 2], [2, 3]])
|
705 |
+
>>> E, Q = mp.eigh(A)
|
706 |
+
>>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0]))
|
707 |
+
[0.0]
|
708 |
+
[0.0]
|
709 |
+
|
710 |
+
>>> A = mp.matrix([[1, 2 + 5j], [2 - 5j, 3]])
|
711 |
+
>>> E, Q = mp.eigh(A)
|
712 |
+
>>> print(mp.chop(A * Q[:,0] - E[0] * Q[:,0]))
|
713 |
+
[0.0]
|
714 |
+
[0.0]
|
715 |
+
|
716 |
+
see also: eigsy, eighe, eig
|
717 |
+
"""
|
718 |
+
|
719 |
+
iscomplex = any(type(x) is ctx.mpc for x in A)
|
720 |
+
|
721 |
+
if iscomplex:
|
722 |
+
return ctx.eighe(A, eigvals_only = eigvals_only, overwrite_a = overwrite_a)
|
723 |
+
else:
|
724 |
+
return ctx.eigsy(A, eigvals_only = eigvals_only, overwrite_a = overwrite_a)
|
725 |
+
|
726 |
+
|
727 |
+
@defun
|
728 |
+
def gauss_quadrature(ctx, n, qtype = "legendre", alpha = 0, beta = 0):
|
729 |
+
"""
|
730 |
+
This routine calulates gaussian quadrature rules for different
|
731 |
+
families of orthogonal polynomials. Let (a, b) be an interval,
|
732 |
+
W(x) a positive weight function and n a positive integer.
|
733 |
+
Then the purpose of this routine is to calculate pairs (x_k, w_k)
|
734 |
+
for k=0, 1, 2, ... (n-1) which give
|
735 |
+
|
736 |
+
int(W(x) * F(x), x = a..b) = sum(w_k * F(x_k),k = 0..(n-1))
|
737 |
+
|
738 |
+
exact for all polynomials F(x) of degree (strictly) less than 2*n. For all
|
739 |
+
integrable functions F(x) the sum is a (more or less) good approximation to
|
740 |
+
the integral. The x_k are called nodes (which are the zeros of the
|
741 |
+
related orthogonal polynomials) and the w_k are called the weights.
|
742 |
+
|
743 |
+
parameters
|
744 |
+
n (input) The degree of the quadrature rule, i.e. its number of
|
745 |
+
nodes.
|
746 |
+
|
747 |
+
qtype (input) The family of orthogonal polynmomials for which to
|
748 |
+
compute the quadrature rule. See the list below.
|
749 |
+
|
750 |
+
alpha (input) real number, used as parameter for some orthogonal
|
751 |
+
polynomials
|
752 |
+
|
753 |
+
beta (input) real number, used as parameter for some orthogonal
|
754 |
+
polynomials.
|
755 |
+
|
756 |
+
return value
|
757 |
+
|
758 |
+
(X, W) a pair of two real arrays where x_k = X[k] and w_k = W[k].
|
759 |
+
|
760 |
+
|
761 |
+
orthogonal polynomials:
|
762 |
+
|
763 |
+
qtype polynomial
|
764 |
+
----- ----------
|
765 |
+
|
766 |
+
"legendre" Legendre polynomials, W(x)=1 on the interval (-1, +1)
|
767 |
+
"legendre01" shifted Legendre polynomials, W(x)=1 on the interval (0, +1)
|
768 |
+
"hermite" Hermite polynomials, W(x)=exp(-x*x) on (-infinity,+infinity)
|
769 |
+
"laguerre" Laguerre polynomials, W(x)=exp(-x) on (0,+infinity)
|
770 |
+
"glaguerre" generalized Laguerre polynomials, W(x)=exp(-x)*x**alpha
|
771 |
+
on (0, +infinity)
|
772 |
+
"chebyshev1" Chebyshev polynomials of the first kind, W(x)=1/sqrt(1-x*x)
|
773 |
+
on (-1, +1)
|
774 |
+
"chebyshev2" Chebyshev polynomials of the second kind, W(x)=sqrt(1-x*x)
|
775 |
+
on (-1, +1)
|
776 |
+
"jacobi" Jacobi polynomials, W(x)=(1-x)**alpha * (1+x)**beta on (-1, +1)
|
777 |
+
with alpha>-1 and beta>-1
|
778 |
+
|
779 |
+
examples:
|
780 |
+
>>> from mpmath import mp
|
781 |
+
>>> f = lambda x: x**8 + 2 * x**6 - 3 * x**4 + 5 * x**2 - 7
|
782 |
+
>>> X, W = mp.gauss_quadrature(5, "hermite")
|
783 |
+
>>> A = mp.fdot([(f(x), w) for x, w in zip(X, W)])
|
784 |
+
>>> B = mp.sqrt(mp.pi) * 57 / 16
|
785 |
+
>>> C = mp.quad(lambda x: mp.exp(- x * x) * f(x), [-mp.inf, +mp.inf])
|
786 |
+
>>> mp.nprint((mp.chop(A-B, tol = 1e-10), mp.chop(A-C, tol = 1e-10)))
|
787 |
+
(0.0, 0.0)
|
788 |
+
|
789 |
+
>>> f = lambda x: x**5 - 2 * x**4 + 3 * x**3 - 5 * x**2 + 7 * x - 11
|
790 |
+
>>> X, W = mp.gauss_quadrature(3, "laguerre")
|
791 |
+
>>> A = mp.fdot([(f(x), w) for x, w in zip(X, W)])
|
792 |
+
>>> B = 76
|
793 |
+
>>> C = mp.quad(lambda x: mp.exp(-x) * f(x), [0, +mp.inf])
|
794 |
+
>>> mp.nprint(mp.chop(A-B, tol = 1e-10), mp.chop(A-C, tol = 1e-10))
|
795 |
+
.0
|
796 |
+
|
797 |
+
# orthogonality of the chebyshev polynomials:
|
798 |
+
>>> f = lambda x: mp.chebyt(3, x) * mp.chebyt(2, x)
|
799 |
+
>>> X, W = mp.gauss_quadrature(3, "chebyshev1")
|
800 |
+
>>> A = mp.fdot([(f(x), w) for x, w in zip(X, W)])
|
801 |
+
>>> print(mp.chop(A, tol = 1e-10))
|
802 |
+
0.0
|
803 |
+
|
804 |
+
references:
|
805 |
+
- golub and welsch, "calculations of gaussian quadrature rules", mathematics of
|
806 |
+
computation 23, p. 221-230 (1969)
|
807 |
+
- golub, "some modified matrix eigenvalue problems", siam review 15, p. 318-334 (1973)
|
808 |
+
- stroud and secrest, "gaussian quadrature formulas", prentice-hall (1966)
|
809 |
+
|
810 |
+
See also the routine gaussq.f in netlog.org or ACM Transactions on
|
811 |
+
Mathematical Software algorithm 726.
|
812 |
+
"""
|
813 |
+
|
814 |
+
d = ctx.zeros(n, 1)
|
815 |
+
e = ctx.zeros(n, 1)
|
816 |
+
z = ctx.zeros(1, n)
|
817 |
+
|
818 |
+
z[0,0] = 1
|
819 |
+
|
820 |
+
if qtype == "legendre":
|
821 |
+
# legendre on the range -1 +1 , abramowitz, table 25.4, p.916
|
822 |
+
w = 2
|
823 |
+
for i in xrange(n):
|
824 |
+
j = i + 1
|
825 |
+
e[i] = ctx.sqrt(j * j / (4 * j * j - ctx.mpf(1)))
|
826 |
+
elif qtype == "legendre01":
|
827 |
+
# legendre shifted to 0 1 , abramowitz, table 25.8, p.921
|
828 |
+
w = 1
|
829 |
+
for i in xrange(n):
|
830 |
+
d[i] = 1 / ctx.mpf(2)
|
831 |
+
j = i + 1
|
832 |
+
e[i] = ctx.sqrt(j * j / (16 * j * j - ctx.mpf(4)))
|
833 |
+
elif qtype == "hermite":
|
834 |
+
# hermite on the range -inf +inf , abramowitz, table 25.10,p.924
|
835 |
+
w = ctx.sqrt(ctx.pi)
|
836 |
+
for i in xrange(n):
|
837 |
+
j = i + 1
|
838 |
+
e[i] = ctx.sqrt(j / ctx.mpf(2))
|
839 |
+
elif qtype == "laguerre":
|
840 |
+
# laguerre on the range 0 +inf , abramowitz, table 25.9, p. 923
|
841 |
+
w = 1
|
842 |
+
for i in xrange(n):
|
843 |
+
j = i + 1
|
844 |
+
d[i] = 2 * j - 1
|
845 |
+
e[i] = j
|
846 |
+
elif qtype=="chebyshev1":
|
847 |
+
# chebyshev polynimials of the first kind
|
848 |
+
w = ctx.pi
|
849 |
+
for i in xrange(n):
|
850 |
+
e[i] = 1 / ctx.mpf(2)
|
851 |
+
e[0] = ctx.sqrt(1 / ctx.mpf(2))
|
852 |
+
elif qtype == "chebyshev2":
|
853 |
+
# chebyshev polynimials of the second kind
|
854 |
+
w = ctx.pi / 2
|
855 |
+
for i in xrange(n):
|
856 |
+
e[i] = 1 / ctx.mpf(2)
|
857 |
+
elif qtype == "glaguerre":
|
858 |
+
# generalized laguerre on the range 0 +inf
|
859 |
+
w = ctx.gamma(1 + alpha)
|
860 |
+
for i in xrange(n):
|
861 |
+
j = i + 1
|
862 |
+
d[i] = 2 * j - 1 + alpha
|
863 |
+
e[i] = ctx.sqrt(j * (j + alpha))
|
864 |
+
elif qtype == "jacobi":
|
865 |
+
# jacobi polynomials
|
866 |
+
alpha = ctx.mpf(alpha)
|
867 |
+
beta = ctx.mpf(beta)
|
868 |
+
ab = alpha + beta
|
869 |
+
abi = ab + 2
|
870 |
+
w = (2**(ab+1)) * ctx.gamma(alpha + 1) * ctx.gamma(beta + 1) / ctx.gamma(abi)
|
871 |
+
d[0] = (beta - alpha) / abi
|
872 |
+
e[0] = ctx.sqrt(4 * (1 + alpha) * (1 + beta) / ((abi + 1) * (abi * abi)))
|
873 |
+
a2b2 = beta * beta - alpha * alpha
|
874 |
+
for i in xrange(1, n):
|
875 |
+
j = i + 1
|
876 |
+
abi = 2 * j + ab
|
877 |
+
d[i] = a2b2 / ((abi - 2) * abi)
|
878 |
+
e[i] = ctx.sqrt(4 * j * (j + alpha) * (j + beta) * (j + ab) / ((abi * abi - 1) * abi * abi))
|
879 |
+
elif isinstance(qtype, str):
|
880 |
+
raise ValueError("unknown quadrature rule \"%s\"" % qtype)
|
881 |
+
elif not isinstance(qtype, str):
|
882 |
+
w = qtype(d, e)
|
883 |
+
else:
|
884 |
+
assert 0
|
885 |
+
|
886 |
+
tridiag_eigen(ctx, d, e, z)
|
887 |
+
|
888 |
+
for i in xrange(len(z)):
|
889 |
+
z[i] *= z[i]
|
890 |
+
|
891 |
+
z = z.transpose()
|
892 |
+
return (d, w * z)
|
893 |
+
|
894 |
+
##################################################################################################
|
895 |
+
##################################################################################################
|
896 |
+
##################################################################################################
|
897 |
+
|
898 |
+
def svd_r_raw(ctx, A, V = False, calc_u = False):
|
899 |
+
"""
|
900 |
+
This routine computes the singular value decomposition of a matrix A.
|
901 |
+
Given A, two orthogonal matrices U and V are calculated such that
|
902 |
+
|
903 |
+
A = U S V
|
904 |
+
|
905 |
+
where S is a suitable shaped matrix whose off-diagonal elements are zero.
|
906 |
+
The diagonal elements of S are the singular values of A, i.e. the
|
907 |
+
squareroots of the eigenvalues of A' A or A A'. Here ' denotes the transpose.
|
908 |
+
Householder bidiagonalization and a variant of the QR algorithm is used.
|
909 |
+
|
910 |
+
overview of the matrices :
|
911 |
+
|
912 |
+
A : m*n A gets replaced by U
|
913 |
+
U : m*n U replaces A. If n>m then only the first m*m block of U is
|
914 |
+
non-zero. column-orthogonal: U' U = B
|
915 |
+
here B is a n*n matrix whose first min(m,n) diagonal
|
916 |
+
elements are 1 and all other elements are zero.
|
917 |
+
S : n*n diagonal matrix, only the diagonal elements are stored in
|
918 |
+
the array S. only the first min(m,n) diagonal elements are non-zero.
|
919 |
+
V : n*n orthogonal: V V' = V' V = 1
|
920 |
+
|
921 |
+
parameters:
|
922 |
+
A (input/output) On input, A contains a real matrix of shape m*n.
|
923 |
+
On output, if calc_u is true A contains the column-orthogonal
|
924 |
+
matrix U; otherwise A is simply used as workspace and thus destroyed.
|
925 |
+
|
926 |
+
V (input/output) if false, the matrix V is not calculated. otherwise
|
927 |
+
V must be a matrix of shape n*n.
|
928 |
+
|
929 |
+
calc_u (input) If true, the matrix U is calculated and replaces A.
|
930 |
+
if false, U is not calculated and A is simply destroyed
|
931 |
+
|
932 |
+
return value:
|
933 |
+
S an array of length n containing the singular values of A sorted by
|
934 |
+
decreasing magnitude. only the first min(m,n) elements are non-zero.
|
935 |
+
|
936 |
+
This routine is a python translation of the fortran routine svd.f in the
|
937 |
+
software library EISPACK (see netlib.org) which itself is based on the
|
938 |
+
algol procedure svd described in:
|
939 |
+
- num. math. 14, 403-420(1970) by golub and reinsch.
|
940 |
+
- wilkinson/reinsch: handbook for auto. comp., vol ii-linear algebra, 134-151(1971).
|
941 |
+
|
942 |
+
"""
|
943 |
+
|
944 |
+
m, n = A.rows, A.cols
|
945 |
+
|
946 |
+
S = ctx.zeros(n, 1)
|
947 |
+
|
948 |
+
# work is a temporary array of size n
|
949 |
+
work = ctx.zeros(n, 1)
|
950 |
+
|
951 |
+
g = scale = anorm = 0
|
952 |
+
maxits = 3 * ctx.dps
|
953 |
+
|
954 |
+
for i in xrange(n): # householder reduction to bidiagonal form
|
955 |
+
work[i] = scale*g
|
956 |
+
g = s = scale = 0
|
957 |
+
if i < m:
|
958 |
+
for k in xrange(i, m):
|
959 |
+
scale += ctx.fabs(A[k,i])
|
960 |
+
if scale != 0:
|
961 |
+
for k in xrange(i, m):
|
962 |
+
A[k,i] /= scale
|
963 |
+
s += A[k,i] * A[k,i]
|
964 |
+
f = A[i,i]
|
965 |
+
g = -ctx.sqrt(s)
|
966 |
+
if f < 0:
|
967 |
+
g = -g
|
968 |
+
h = f * g - s
|
969 |
+
A[i,i] = f - g
|
970 |
+
for j in xrange(i+1, n):
|
971 |
+
s = 0
|
972 |
+
for k in xrange(i, m):
|
973 |
+
s += A[k,i] * A[k,j]
|
974 |
+
f = s / h
|
975 |
+
for k in xrange(i, m):
|
976 |
+
A[k,j] += f * A[k,i]
|
977 |
+
for k in xrange(i,m):
|
978 |
+
A[k,i] *= scale
|
979 |
+
|
980 |
+
S[i] = scale * g
|
981 |
+
g = s = scale = 0
|
982 |
+
|
983 |
+
if i < m and i != n - 1:
|
984 |
+
for k in xrange(i+1, n):
|
985 |
+
scale += ctx.fabs(A[i,k])
|
986 |
+
if scale:
|
987 |
+
for k in xrange(i+1, n):
|
988 |
+
A[i,k] /= scale
|
989 |
+
s += A[i,k] * A[i,k]
|
990 |
+
f = A[i,i+1]
|
991 |
+
g = -ctx.sqrt(s)
|
992 |
+
if f < 0:
|
993 |
+
g = -g
|
994 |
+
h = f * g - s
|
995 |
+
A[i,i+1] = f - g
|
996 |
+
|
997 |
+
for k in xrange(i+1, n):
|
998 |
+
work[k] = A[i,k] / h
|
999 |
+
|
1000 |
+
for j in xrange(i+1, m):
|
1001 |
+
s = 0
|
1002 |
+
for k in xrange(i+1, n):
|
1003 |
+
s += A[j,k] * A[i,k]
|
1004 |
+
for k in xrange(i+1, n):
|
1005 |
+
A[j,k] += s * work[k]
|
1006 |
+
|
1007 |
+
for k in xrange(i+1, n):
|
1008 |
+
A[i,k] *= scale
|
1009 |
+
|
1010 |
+
anorm = max(anorm, ctx.fabs(S[i]) + ctx.fabs(work[i]))
|
1011 |
+
|
1012 |
+
if not isinstance(V, bool):
|
1013 |
+
for i in xrange(n-2, -1, -1): # accumulation of right hand transformations
|
1014 |
+
V[i+1,i+1] = 1
|
1015 |
+
|
1016 |
+
if work[i+1] != 0:
|
1017 |
+
for j in xrange(i+1, n):
|
1018 |
+
V[i,j] = (A[i,j] / A[i,i+1]) / work[i+1]
|
1019 |
+
for j in xrange(i+1, n):
|
1020 |
+
s = 0
|
1021 |
+
for k in xrange(i+1, n):
|
1022 |
+
s += A[i,k] * V[j,k]
|
1023 |
+
for k in xrange(i+1, n):
|
1024 |
+
V[j,k] += s * V[i,k]
|
1025 |
+
|
1026 |
+
for j in xrange(i+1, n):
|
1027 |
+
V[j,i] = V[i,j] = 0
|
1028 |
+
|
1029 |
+
V[0,0] = 1
|
1030 |
+
|
1031 |
+
if m<n : minnm = m
|
1032 |
+
else : minnm = n
|
1033 |
+
|
1034 |
+
if calc_u:
|
1035 |
+
for i in xrange(minnm-1, -1, -1): # accumulation of left hand transformations
|
1036 |
+
g = S[i]
|
1037 |
+
for j in xrange(i+1, n):
|
1038 |
+
A[i,j] = 0
|
1039 |
+
if g != 0:
|
1040 |
+
g = 1 / g
|
1041 |
+
for j in xrange(i+1, n):
|
1042 |
+
s = 0
|
1043 |
+
for k in xrange(i+1, m):
|
1044 |
+
s += A[k,i] * A[k,j]
|
1045 |
+
f = (s / A[i,i]) * g
|
1046 |
+
for k in xrange(i, m):
|
1047 |
+
A[k,j] += f * A[k,i]
|
1048 |
+
for j in xrange(i, m):
|
1049 |
+
A[j,i] *= g
|
1050 |
+
else:
|
1051 |
+
for j in xrange(i, m):
|
1052 |
+
A[j,i] = 0
|
1053 |
+
A[i,i] += 1
|
1054 |
+
|
1055 |
+
for k in xrange(n - 1, -1, -1):
|
1056 |
+
# diagonalization of the bidiagonal form:
|
1057 |
+
# loop over singular values, and over allowed itations
|
1058 |
+
|
1059 |
+
its = 0
|
1060 |
+
while 1:
|
1061 |
+
its += 1
|
1062 |
+
flag = True
|
1063 |
+
|
1064 |
+
for l in xrange(k, -1, -1):
|
1065 |
+
nm = l-1
|
1066 |
+
|
1067 |
+
if ctx.fabs(work[l]) + anorm == anorm:
|
1068 |
+
flag = False
|
1069 |
+
break
|
1070 |
+
|
1071 |
+
if ctx.fabs(S[nm]) + anorm == anorm:
|
1072 |
+
break
|
1073 |
+
|
1074 |
+
if flag:
|
1075 |
+
c = 0
|
1076 |
+
s = 1
|
1077 |
+
for i in xrange(l, k + 1):
|
1078 |
+
f = s * work[i]
|
1079 |
+
work[i] *= c
|
1080 |
+
if ctx.fabs(f) + anorm == anorm:
|
1081 |
+
break
|
1082 |
+
g = S[i]
|
1083 |
+
h = ctx.hypot(f, g)
|
1084 |
+
S[i] = h
|
1085 |
+
h = 1 / h
|
1086 |
+
c = g * h
|
1087 |
+
s = - f * h
|
1088 |
+
|
1089 |
+
if calc_u:
|
1090 |
+
for j in xrange(m):
|
1091 |
+
y = A[j,nm]
|
1092 |
+
z = A[j,i]
|
1093 |
+
A[j,nm] = y * c + z * s
|
1094 |
+
A[j,i] = z * c - y * s
|
1095 |
+
|
1096 |
+
z = S[k]
|
1097 |
+
|
1098 |
+
if l == k: # convergence
|
1099 |
+
if z < 0: # singular value is made nonnegative
|
1100 |
+
S[k] = -z
|
1101 |
+
if not isinstance(V, bool):
|
1102 |
+
for j in xrange(n):
|
1103 |
+
V[k,j] = -V[k,j]
|
1104 |
+
break
|
1105 |
+
|
1106 |
+
if its >= maxits:
|
1107 |
+
raise RuntimeError("svd: no convergence to an eigenvalue after %d iterations" % its)
|
1108 |
+
|
1109 |
+
x = S[l] # shift from bottom 2 by 2 minor
|
1110 |
+
nm = k-1
|
1111 |
+
y = S[nm]
|
1112 |
+
g = work[nm]
|
1113 |
+
h = work[k]
|
1114 |
+
f = ((y - z) * (y + z) + (g - h) * (g + h))/(2 * h * y)
|
1115 |
+
g = ctx.hypot(f, 1)
|
1116 |
+
if f >= 0: f = ((x - z) * (x + z) + h * ((y / (f + g)) - h)) / x
|
1117 |
+
else: f = ((x - z) * (x + z) + h * ((y / (f - g)) - h)) / x
|
1118 |
+
|
1119 |
+
c = s = 1 # next qt transformation
|
1120 |
+
|
1121 |
+
for j in xrange(l, nm + 1):
|
1122 |
+
g = work[j+1]
|
1123 |
+
y = S[j+1]
|
1124 |
+
h = s * g
|
1125 |
+
g = c * g
|
1126 |
+
z = ctx.hypot(f, h)
|
1127 |
+
work[j] = z
|
1128 |
+
c = f / z
|
1129 |
+
s = h / z
|
1130 |
+
f = x * c + g * s
|
1131 |
+
g = g * c - x * s
|
1132 |
+
h = y * s
|
1133 |
+
y *= c
|
1134 |
+
if not isinstance(V, bool):
|
1135 |
+
for jj in xrange(n):
|
1136 |
+
x = V[j ,jj]
|
1137 |
+
z = V[j+1,jj]
|
1138 |
+
V[j ,jj]= x * c + z * s
|
1139 |
+
V[j+1 ,jj]= z * c - x * s
|
1140 |
+
z = ctx.hypot(f, h)
|
1141 |
+
S[j] = z
|
1142 |
+
if z != 0: # rotation can be arbitray if z=0
|
1143 |
+
z = 1 / z
|
1144 |
+
c = f * z
|
1145 |
+
s = h * z
|
1146 |
+
f = c * g + s * y
|
1147 |
+
x = c * y - s * g
|
1148 |
+
|
1149 |
+
if calc_u:
|
1150 |
+
for jj in xrange(m):
|
1151 |
+
y = A[jj,j ]
|
1152 |
+
z = A[jj,j+1]
|
1153 |
+
A[jj,j ] = y * c + z * s
|
1154 |
+
A[jj,j+1 ] = z * c - y * s
|
1155 |
+
|
1156 |
+
work[l] = 0
|
1157 |
+
work[k] = f
|
1158 |
+
S[k] = x
|
1159 |
+
|
1160 |
+
##########################
|
1161 |
+
|
1162 |
+
# Sort singular values into decreasing order (bubble-sort)
|
1163 |
+
|
1164 |
+
for i in xrange(n):
|
1165 |
+
imax = i
|
1166 |
+
s = ctx.fabs(S[i]) # s is the current maximal element
|
1167 |
+
|
1168 |
+
for j in xrange(i + 1, n):
|
1169 |
+
c = ctx.fabs(S[j])
|
1170 |
+
if c > s:
|
1171 |
+
s = c
|
1172 |
+
imax = j
|
1173 |
+
|
1174 |
+
if imax != i:
|
1175 |
+
# swap singular values
|
1176 |
+
|
1177 |
+
z = S[i]
|
1178 |
+
S[i] = S[imax]
|
1179 |
+
S[imax] = z
|
1180 |
+
|
1181 |
+
if calc_u:
|
1182 |
+
for j in xrange(m):
|
1183 |
+
z = A[j,i]
|
1184 |
+
A[j,i] = A[j,imax]
|
1185 |
+
A[j,imax] = z
|
1186 |
+
|
1187 |
+
if not isinstance(V, bool):
|
1188 |
+
for j in xrange(n):
|
1189 |
+
z = V[i,j]
|
1190 |
+
V[i,j] = V[imax,j]
|
1191 |
+
V[imax,j] = z
|
1192 |
+
|
1193 |
+
return S
|
1194 |
+
|
1195 |
+
#######################
|
1196 |
+
|
1197 |
+
def svd_c_raw(ctx, A, V = False, calc_u = False):
|
1198 |
+
"""
|
1199 |
+
This routine computes the singular value decomposition of a matrix A.
|
1200 |
+
Given A, two unitary matrices U and V are calculated such that
|
1201 |
+
|
1202 |
+
A = U S V
|
1203 |
+
|
1204 |
+
where S is a suitable shaped matrix whose off-diagonal elements are zero.
|
1205 |
+
The diagonal elements of S are the singular values of A, i.e. the
|
1206 |
+
squareroots of the eigenvalues of A' A or A A'. Here ' denotes the hermitian
|
1207 |
+
transpose (i.e. transposition and conjugation). Householder bidiagonalization
|
1208 |
+
and a variant of the QR algorithm is used.
|
1209 |
+
|
1210 |
+
overview of the matrices :
|
1211 |
+
|
1212 |
+
A : m*n A gets replaced by U
|
1213 |
+
U : m*n U replaces A. If n>m then only the first m*m block of U is
|
1214 |
+
non-zero. column-unitary: U' U = B
|
1215 |
+
here B is a n*n matrix whose first min(m,n) diagonal
|
1216 |
+
elements are 1 and all other elements are zero.
|
1217 |
+
S : n*n diagonal matrix, only the diagonal elements are stored in
|
1218 |
+
the array S. only the first min(m,n) diagonal elements are non-zero.
|
1219 |
+
V : n*n unitary: V V' = V' V = 1
|
1220 |
+
|
1221 |
+
parameters:
|
1222 |
+
A (input/output) On input, A contains a complex matrix of shape m*n.
|
1223 |
+
On output, if calc_u is true A contains the column-unitary
|
1224 |
+
matrix U; otherwise A is simply used as workspace and thus destroyed.
|
1225 |
+
|
1226 |
+
V (input/output) if false, the matrix V is not calculated. otherwise
|
1227 |
+
V must be a matrix of shape n*n.
|
1228 |
+
|
1229 |
+
calc_u (input) If true, the matrix U is calculated and replaces A.
|
1230 |
+
if false, U is not calculated and A is simply destroyed
|
1231 |
+
|
1232 |
+
return value:
|
1233 |
+
S an array of length n containing the singular values of A sorted by
|
1234 |
+
decreasing magnitude. only the first min(m,n) elements are non-zero.
|
1235 |
+
|
1236 |
+
This routine is a python translation of the fortran routine svd.f in the
|
1237 |
+
software library EISPACK (see netlib.org) which itself is based on the
|
1238 |
+
algol procedure svd described in:
|
1239 |
+
- num. math. 14, 403-420(1970) by golub and reinsch.
|
1240 |
+
- wilkinson/reinsch: handbook for auto. comp., vol ii-linear algebra, 134-151(1971).
|
1241 |
+
|
1242 |
+
"""
|
1243 |
+
|
1244 |
+
m, n = A.rows, A.cols
|
1245 |
+
|
1246 |
+
S = ctx.zeros(n, 1)
|
1247 |
+
|
1248 |
+
# work is a temporary array of size n
|
1249 |
+
work = ctx.zeros(n, 1)
|
1250 |
+
lbeta = ctx.zeros(n, 1)
|
1251 |
+
rbeta = ctx.zeros(n, 1)
|
1252 |
+
dwork = ctx.zeros(n, 1)
|
1253 |
+
|
1254 |
+
g = scale = anorm = 0
|
1255 |
+
maxits = 3 * ctx.dps
|
1256 |
+
|
1257 |
+
for i in xrange(n): # householder reduction to bidiagonal form
|
1258 |
+
dwork[i] = scale * g # dwork are the side-diagonal elements
|
1259 |
+
g = s = scale = 0
|
1260 |
+
if i < m:
|
1261 |
+
for k in xrange(i, m):
|
1262 |
+
scale += ctx.fabs(ctx.re(A[k,i])) + ctx.fabs(ctx.im(A[k,i]))
|
1263 |
+
if scale != 0:
|
1264 |
+
for k in xrange(i, m):
|
1265 |
+
A[k,i] /= scale
|
1266 |
+
ar = ctx.re(A[k,i])
|
1267 |
+
ai = ctx.im(A[k,i])
|
1268 |
+
s += ar * ar + ai * ai
|
1269 |
+
f = A[i,i]
|
1270 |
+
g = -ctx.sqrt(s)
|
1271 |
+
if ctx.re(f) < 0:
|
1272 |
+
beta = -g - ctx.conj(f)
|
1273 |
+
g = -g
|
1274 |
+
else:
|
1275 |
+
beta = -g + ctx.conj(f)
|
1276 |
+
beta /= ctx.conj(beta)
|
1277 |
+
beta += 1
|
1278 |
+
h = 2 * (ctx.re(f) * g - s)
|
1279 |
+
A[i,i] = f - g
|
1280 |
+
beta /= h
|
1281 |
+
lbeta[i] = (beta / scale) / scale
|
1282 |
+
for j in xrange(i+1, n):
|
1283 |
+
s = 0
|
1284 |
+
for k in xrange(i, m):
|
1285 |
+
s += ctx.conj(A[k,i]) * A[k,j]
|
1286 |
+
f = beta * s
|
1287 |
+
for k in xrange(i, m):
|
1288 |
+
A[k,j] += f * A[k,i]
|
1289 |
+
for k in xrange(i, m):
|
1290 |
+
A[k,i] *= scale
|
1291 |
+
|
1292 |
+
S[i] = scale * g # S are the diagonal elements
|
1293 |
+
g = s = scale = 0
|
1294 |
+
|
1295 |
+
if i < m and i != n - 1:
|
1296 |
+
for k in xrange(i+1, n):
|
1297 |
+
scale += ctx.fabs(ctx.re(A[i,k])) + ctx.fabs(ctx.im(A[i,k]))
|
1298 |
+
if scale:
|
1299 |
+
for k in xrange(i+1, n):
|
1300 |
+
A[i,k] /= scale
|
1301 |
+
ar = ctx.re(A[i,k])
|
1302 |
+
ai = ctx.im(A[i,k])
|
1303 |
+
s += ar * ar + ai * ai
|
1304 |
+
f = A[i,i+1]
|
1305 |
+
g = -ctx.sqrt(s)
|
1306 |
+
if ctx.re(f) < 0:
|
1307 |
+
beta = -g - ctx.conj(f)
|
1308 |
+
g = -g
|
1309 |
+
else:
|
1310 |
+
beta = -g + ctx.conj(f)
|
1311 |
+
|
1312 |
+
beta /= ctx.conj(beta)
|
1313 |
+
beta += 1
|
1314 |
+
|
1315 |
+
h = 2 * (ctx.re(f) * g - s)
|
1316 |
+
A[i,i+1] = f - g
|
1317 |
+
|
1318 |
+
beta /= h
|
1319 |
+
rbeta[i] = (beta / scale) / scale
|
1320 |
+
|
1321 |
+
for k in xrange(i+1, n):
|
1322 |
+
work[k] = A[i, k]
|
1323 |
+
|
1324 |
+
for j in xrange(i+1, m):
|
1325 |
+
s = 0
|
1326 |
+
for k in xrange(i+1, n):
|
1327 |
+
s += ctx.conj(A[i,k]) * A[j,k]
|
1328 |
+
f = s * beta
|
1329 |
+
for k in xrange(i+1,n):
|
1330 |
+
A[j,k] += f * work[k]
|
1331 |
+
|
1332 |
+
for k in xrange(i+1, n):
|
1333 |
+
A[i,k] *= scale
|
1334 |
+
|
1335 |
+
anorm = max(anorm,ctx.fabs(S[i]) + ctx.fabs(dwork[i]))
|
1336 |
+
|
1337 |
+
if not isinstance(V, bool):
|
1338 |
+
for i in xrange(n-2, -1, -1): # accumulation of right hand transformations
|
1339 |
+
V[i+1,i+1] = 1
|
1340 |
+
|
1341 |
+
if dwork[i+1] != 0:
|
1342 |
+
f = ctx.conj(rbeta[i])
|
1343 |
+
for j in xrange(i+1, n):
|
1344 |
+
V[i,j] = A[i,j] * f
|
1345 |
+
for j in xrange(i+1, n):
|
1346 |
+
s = 0
|
1347 |
+
for k in xrange(i+1, n):
|
1348 |
+
s += ctx.conj(A[i,k]) * V[j,k]
|
1349 |
+
for k in xrange(i+1, n):
|
1350 |
+
V[j,k] += s * V[i,k]
|
1351 |
+
|
1352 |
+
for j in xrange(i+1,n):
|
1353 |
+
V[j,i] = V[i,j] = 0
|
1354 |
+
|
1355 |
+
V[0,0] = 1
|
1356 |
+
|
1357 |
+
if m < n : minnm = m
|
1358 |
+
else : minnm = n
|
1359 |
+
|
1360 |
+
if calc_u:
|
1361 |
+
for i in xrange(minnm-1, -1, -1): # accumulation of left hand transformations
|
1362 |
+
g = S[i]
|
1363 |
+
for j in xrange(i+1, n):
|
1364 |
+
A[i,j] = 0
|
1365 |
+
if g != 0:
|
1366 |
+
g = 1 / g
|
1367 |
+
for j in xrange(i+1, n):
|
1368 |
+
s = 0
|
1369 |
+
for k in xrange(i+1, m):
|
1370 |
+
s += ctx.conj(A[k,i]) * A[k,j]
|
1371 |
+
f = s * ctx.conj(lbeta[i])
|
1372 |
+
for k in xrange(i, m):
|
1373 |
+
A[k,j] += f * A[k,i]
|
1374 |
+
for j in xrange(i, m):
|
1375 |
+
A[j,i] *= g
|
1376 |
+
else:
|
1377 |
+
for j in xrange(i, m):
|
1378 |
+
A[j,i] = 0
|
1379 |
+
A[i,i] += 1
|
1380 |
+
|
1381 |
+
for k in xrange(n-1, -1, -1):
|
1382 |
+
# diagonalization of the bidiagonal form:
|
1383 |
+
# loop over singular values, and over allowed itations
|
1384 |
+
|
1385 |
+
its = 0
|
1386 |
+
while 1:
|
1387 |
+
its += 1
|
1388 |
+
flag = True
|
1389 |
+
|
1390 |
+
for l in xrange(k, -1, -1):
|
1391 |
+
nm = l - 1
|
1392 |
+
|
1393 |
+
if ctx.fabs(dwork[l]) + anorm == anorm:
|
1394 |
+
flag = False
|
1395 |
+
break
|
1396 |
+
|
1397 |
+
if ctx.fabs(S[nm]) + anorm == anorm:
|
1398 |
+
break
|
1399 |
+
|
1400 |
+
if flag:
|
1401 |
+
c = 0
|
1402 |
+
s = 1
|
1403 |
+
for i in xrange(l, k+1):
|
1404 |
+
f = s * dwork[i]
|
1405 |
+
dwork[i] *= c
|
1406 |
+
if ctx.fabs(f) + anorm == anorm:
|
1407 |
+
break
|
1408 |
+
g = S[i]
|
1409 |
+
h = ctx.hypot(f, g)
|
1410 |
+
S[i] = h
|
1411 |
+
h = 1 / h
|
1412 |
+
c = g * h
|
1413 |
+
s = -f * h
|
1414 |
+
|
1415 |
+
if calc_u:
|
1416 |
+
for j in xrange(m):
|
1417 |
+
y = A[j,nm]
|
1418 |
+
z = A[j,i]
|
1419 |
+
A[j,nm]= y * c + z * s
|
1420 |
+
A[j,i] = z * c - y * s
|
1421 |
+
|
1422 |
+
z = S[k]
|
1423 |
+
|
1424 |
+
if l == k: # convergence
|
1425 |
+
if z < 0: # singular value is made nonnegative
|
1426 |
+
S[k] = -z
|
1427 |
+
if not isinstance(V, bool):
|
1428 |
+
for j in xrange(n):
|
1429 |
+
V[k,j] = -V[k,j]
|
1430 |
+
break
|
1431 |
+
|
1432 |
+
if its >= maxits:
|
1433 |
+
raise RuntimeError("svd: no convergence to an eigenvalue after %d iterations" % its)
|
1434 |
+
|
1435 |
+
x = S[l] # shift from bottom 2 by 2 minor
|
1436 |
+
nm = k-1
|
1437 |
+
y = S[nm]
|
1438 |
+
g = dwork[nm]
|
1439 |
+
h = dwork[k]
|
1440 |
+
f = ((y - z) * (y + z) + (g - h) * (g + h)) / (2 * h * y)
|
1441 |
+
g = ctx.hypot(f, 1)
|
1442 |
+
if f >=0: f = (( x - z) *( x + z) + h *((y / (f + g)) - h)) / x
|
1443 |
+
else: f = (( x - z) *( x + z) + h *((y / (f - g)) - h)) / x
|
1444 |
+
|
1445 |
+
c = s = 1 # next qt transformation
|
1446 |
+
|
1447 |
+
for j in xrange(l, nm + 1):
|
1448 |
+
g = dwork[j+1]
|
1449 |
+
y = S[j+1]
|
1450 |
+
h = s * g
|
1451 |
+
g = c * g
|
1452 |
+
z = ctx.hypot(f, h)
|
1453 |
+
dwork[j] = z
|
1454 |
+
c = f / z
|
1455 |
+
s = h / z
|
1456 |
+
f = x * c + g * s
|
1457 |
+
g = g * c - x * s
|
1458 |
+
h = y * s
|
1459 |
+
y *= c
|
1460 |
+
if not isinstance(V, bool):
|
1461 |
+
for jj in xrange(n):
|
1462 |
+
x = V[j ,jj]
|
1463 |
+
z = V[j+1,jj]
|
1464 |
+
V[j ,jj]= x * c + z * s
|
1465 |
+
V[j+1,jj ]= z * c - x * s
|
1466 |
+
z = ctx.hypot(f, h)
|
1467 |
+
S[j] = z
|
1468 |
+
if z != 0: # rotation can be arbitray if z=0
|
1469 |
+
z = 1 / z
|
1470 |
+
c = f * z
|
1471 |
+
s = h * z
|
1472 |
+
f = c * g + s * y
|
1473 |
+
x = c * y - s * g
|
1474 |
+
if calc_u:
|
1475 |
+
for jj in xrange(m):
|
1476 |
+
y = A[jj,j ]
|
1477 |
+
z = A[jj,j+1]
|
1478 |
+
A[jj,j ]= y * c + z * s
|
1479 |
+
A[jj,j+1 ]= z * c - y * s
|
1480 |
+
|
1481 |
+
dwork[l] = 0
|
1482 |
+
dwork[k] = f
|
1483 |
+
S[k] = x
|
1484 |
+
|
1485 |
+
##########################
|
1486 |
+
|
1487 |
+
# Sort singular values into decreasing order (bubble-sort)
|
1488 |
+
|
1489 |
+
for i in xrange(n):
|
1490 |
+
imax = i
|
1491 |
+
s = ctx.fabs(S[i]) # s is the current maximal element
|
1492 |
+
|
1493 |
+
for j in xrange(i + 1, n):
|
1494 |
+
c = ctx.fabs(S[j])
|
1495 |
+
if c > s:
|
1496 |
+
s = c
|
1497 |
+
imax = j
|
1498 |
+
|
1499 |
+
if imax != i:
|
1500 |
+
# swap singular values
|
1501 |
+
|
1502 |
+
z = S[i]
|
1503 |
+
S[i] = S[imax]
|
1504 |
+
S[imax] = z
|
1505 |
+
|
1506 |
+
if calc_u:
|
1507 |
+
for j in xrange(m):
|
1508 |
+
z = A[j,i]
|
1509 |
+
A[j,i] = A[j,imax]
|
1510 |
+
A[j,imax] = z
|
1511 |
+
|
1512 |
+
if not isinstance(V, bool):
|
1513 |
+
for j in xrange(n):
|
1514 |
+
z = V[i,j]
|
1515 |
+
V[i,j] = V[imax,j]
|
1516 |
+
V[imax,j] = z
|
1517 |
+
|
1518 |
+
return S
|
1519 |
+
|
1520 |
+
##################################################################################################
|
1521 |
+
|
1522 |
+
@defun
|
1523 |
+
def svd_r(ctx, A, full_matrices = False, compute_uv = True, overwrite_a = False):
|
1524 |
+
"""
|
1525 |
+
This routine computes the singular value decomposition of a matrix A.
|
1526 |
+
Given A, two orthogonal matrices U and V are calculated such that
|
1527 |
+
|
1528 |
+
A = U S V and U' U = 1 and V V' = 1
|
1529 |
+
|
1530 |
+
where S is a suitable shaped matrix whose off-diagonal elements are zero.
|
1531 |
+
Here ' denotes the transpose. The diagonal elements of S are the singular
|
1532 |
+
values of A, i.e. the squareroots of the eigenvalues of A' A or A A'.
|
1533 |
+
|
1534 |
+
input:
|
1535 |
+
A : a real matrix of shape (m, n)
|
1536 |
+
full_matrices : if true, U and V are of shape (m, m) and (n, n).
|
1537 |
+
if false, U and V are of shape (m, min(m, n)) and (min(m, n), n).
|
1538 |
+
compute_uv : if true, U and V are calculated. if false, only S is calculated.
|
1539 |
+
overwrite_a : if true, allows modification of A which may improve
|
1540 |
+
performance. if false, A is not modified.
|
1541 |
+
|
1542 |
+
output:
|
1543 |
+
U : an orthogonal matrix: U' U = 1. if full_matrices is true, U is of
|
1544 |
+
shape (m, m). ortherwise it is of shape (m, min(m, n)).
|
1545 |
+
|
1546 |
+
S : an array of length min(m, n) containing the singular values of A sorted by
|
1547 |
+
decreasing magnitude.
|
1548 |
+
|
1549 |
+
V : an orthogonal matrix: V V' = 1. if full_matrices is true, V is of
|
1550 |
+
shape (n, n). ortherwise it is of shape (min(m, n), n).
|
1551 |
+
|
1552 |
+
return value:
|
1553 |
+
|
1554 |
+
S if compute_uv is false
|
1555 |
+
(U, S, V) if compute_uv is true
|
1556 |
+
|
1557 |
+
overview of the matrices:
|
1558 |
+
|
1559 |
+
full_matrices true:
|
1560 |
+
A : m*n
|
1561 |
+
U : m*m U' U = 1
|
1562 |
+
S as matrix : m*n
|
1563 |
+
V : n*n V V' = 1
|
1564 |
+
|
1565 |
+
full_matrices false:
|
1566 |
+
A : m*n
|
1567 |
+
U : m*min(n,m) U' U = 1
|
1568 |
+
S as matrix : min(m,n)*min(m,n)
|
1569 |
+
V : min(m,n)*n V V' = 1
|
1570 |
+
|
1571 |
+
examples:
|
1572 |
+
|
1573 |
+
>>> from mpmath import mp
|
1574 |
+
>>> A = mp.matrix([[2, -2, -1], [3, 4, -2], [-2, -2, 0]])
|
1575 |
+
>>> S = mp.svd_r(A, compute_uv = False)
|
1576 |
+
>>> print(S)
|
1577 |
+
[6.0]
|
1578 |
+
[3.0]
|
1579 |
+
[1.0]
|
1580 |
+
|
1581 |
+
>>> U, S, V = mp.svd_r(A)
|
1582 |
+
>>> print(mp.chop(A - U * mp.diag(S) * V))
|
1583 |
+
[0.0 0.0 0.0]
|
1584 |
+
[0.0 0.0 0.0]
|
1585 |
+
[0.0 0.0 0.0]
|
1586 |
+
|
1587 |
+
|
1588 |
+
see also: svd, svd_c
|
1589 |
+
"""
|
1590 |
+
|
1591 |
+
m, n = A.rows, A.cols
|
1592 |
+
|
1593 |
+
if not compute_uv:
|
1594 |
+
if not overwrite_a:
|
1595 |
+
A = A.copy()
|
1596 |
+
S = svd_r_raw(ctx, A, V = False, calc_u = False)
|
1597 |
+
S = S[:min(m,n)]
|
1598 |
+
return S
|
1599 |
+
|
1600 |
+
if full_matrices and n < m:
|
1601 |
+
V = ctx.zeros(m, m)
|
1602 |
+
A0 = ctx.zeros(m, m)
|
1603 |
+
A0[:,:n] = A
|
1604 |
+
S = svd_r_raw(ctx, A0, V, calc_u = True)
|
1605 |
+
|
1606 |
+
S = S[:n]
|
1607 |
+
V = V[:n,:n]
|
1608 |
+
|
1609 |
+
return (A0, S, V)
|
1610 |
+
else:
|
1611 |
+
if not overwrite_a:
|
1612 |
+
A = A.copy()
|
1613 |
+
V = ctx.zeros(n, n)
|
1614 |
+
S = svd_r_raw(ctx, A, V, calc_u = True)
|
1615 |
+
|
1616 |
+
if n > m:
|
1617 |
+
if full_matrices == False:
|
1618 |
+
V = V[:m,:]
|
1619 |
+
|
1620 |
+
S = S[:m]
|
1621 |
+
A = A[:,:m]
|
1622 |
+
|
1623 |
+
return (A, S, V)
|
1624 |
+
|
1625 |
+
##############################
|
1626 |
+
|
1627 |
+
@defun
|
1628 |
+
def svd_c(ctx, A, full_matrices = False, compute_uv = True, overwrite_a = False):
|
1629 |
+
"""
|
1630 |
+
This routine computes the singular value decomposition of a matrix A.
|
1631 |
+
Given A, two unitary matrices U and V are calculated such that
|
1632 |
+
|
1633 |
+
A = U S V and U' U = 1 and V V' = 1
|
1634 |
+
|
1635 |
+
where S is a suitable shaped matrix whose off-diagonal elements are zero.
|
1636 |
+
Here ' denotes the hermitian transpose (i.e. transposition and complex
|
1637 |
+
conjugation). The diagonal elements of S are the singular values of A,
|
1638 |
+
i.e. the squareroots of the eigenvalues of A' A or A A'.
|
1639 |
+
|
1640 |
+
input:
|
1641 |
+
A : a complex matrix of shape (m, n)
|
1642 |
+
full_matrices : if true, U and V are of shape (m, m) and (n, n).
|
1643 |
+
if false, U and V are of shape (m, min(m, n)) and (min(m, n), n).
|
1644 |
+
compute_uv : if true, U and V are calculated. if false, only S is calculated.
|
1645 |
+
overwrite_a : if true, allows modification of A which may improve
|
1646 |
+
performance. if false, A is not modified.
|
1647 |
+
|
1648 |
+
output:
|
1649 |
+
U : an unitary matrix: U' U = 1. if full_matrices is true, U is of
|
1650 |
+
shape (m, m). ortherwise it is of shape (m, min(m, n)).
|
1651 |
+
|
1652 |
+
S : an array of length min(m, n) containing the singular values of A sorted by
|
1653 |
+
decreasing magnitude.
|
1654 |
+
|
1655 |
+
V : an unitary matrix: V V' = 1. if full_matrices is true, V is of
|
1656 |
+
shape (n, n). ortherwise it is of shape (min(m, n), n).
|
1657 |
+
|
1658 |
+
return value:
|
1659 |
+
|
1660 |
+
S if compute_uv is false
|
1661 |
+
(U, S, V) if compute_uv is true
|
1662 |
+
|
1663 |
+
overview of the matrices:
|
1664 |
+
|
1665 |
+
full_matrices true:
|
1666 |
+
A : m*n
|
1667 |
+
U : m*m U' U = 1
|
1668 |
+
S as matrix : m*n
|
1669 |
+
V : n*n V V' = 1
|
1670 |
+
|
1671 |
+
full_matrices false:
|
1672 |
+
A : m*n
|
1673 |
+
U : m*min(n,m) U' U = 1
|
1674 |
+
S as matrix : min(m,n)*min(m,n)
|
1675 |
+
V : min(m,n)*n V V' = 1
|
1676 |
+
|
1677 |
+
example:
|
1678 |
+
>>> from mpmath import mp
|
1679 |
+
>>> A = mp.matrix([[-2j, -1-3j, -2+2j], [2-2j, -1-3j, 1], [-3+1j,-2j,0]])
|
1680 |
+
>>> S = mp.svd_c(A, compute_uv = False)
|
1681 |
+
>>> print(mp.chop(S - mp.matrix([mp.sqrt(34), mp.sqrt(15), mp.sqrt(6)])))
|
1682 |
+
[0.0]
|
1683 |
+
[0.0]
|
1684 |
+
[0.0]
|
1685 |
+
|
1686 |
+
>>> U, S, V = mp.svd_c(A)
|
1687 |
+
>>> print(mp.chop(A - U * mp.diag(S) * V))
|
1688 |
+
[0.0 0.0 0.0]
|
1689 |
+
[0.0 0.0 0.0]
|
1690 |
+
[0.0 0.0 0.0]
|
1691 |
+
|
1692 |
+
see also: svd, svd_r
|
1693 |
+
"""
|
1694 |
+
|
1695 |
+
m, n = A.rows, A.cols
|
1696 |
+
|
1697 |
+
if not compute_uv:
|
1698 |
+
if not overwrite_a:
|
1699 |
+
A = A.copy()
|
1700 |
+
S = svd_c_raw(ctx, A, V = False, calc_u = False)
|
1701 |
+
S = S[:min(m,n)]
|
1702 |
+
return S
|
1703 |
+
|
1704 |
+
if full_matrices and n < m:
|
1705 |
+
V = ctx.zeros(m, m)
|
1706 |
+
A0 = ctx.zeros(m, m)
|
1707 |
+
A0[:,:n] = A
|
1708 |
+
S = svd_c_raw(ctx, A0, V, calc_u = True)
|
1709 |
+
|
1710 |
+
S = S[:n]
|
1711 |
+
V = V[:n,:n]
|
1712 |
+
|
1713 |
+
return (A0, S, V)
|
1714 |
+
else:
|
1715 |
+
if not overwrite_a:
|
1716 |
+
A = A.copy()
|
1717 |
+
V = ctx.zeros(n, n)
|
1718 |
+
S = svd_c_raw(ctx, A, V, calc_u = True)
|
1719 |
+
|
1720 |
+
if n > m:
|
1721 |
+
if full_matrices == False:
|
1722 |
+
V = V[:m,:]
|
1723 |
+
|
1724 |
+
S = S[:m]
|
1725 |
+
A = A[:,:m]
|
1726 |
+
|
1727 |
+
return (A, S, V)
|
1728 |
+
|
1729 |
+
@defun
|
1730 |
+
def svd(ctx, A, full_matrices = False, compute_uv = True, overwrite_a = False):
|
1731 |
+
"""
|
1732 |
+
"svd" is a unified interface for "svd_r" and "svd_c". Depending on
|
1733 |
+
whether A is real or complex the appropriate function is called.
|
1734 |
+
|
1735 |
+
This routine computes the singular value decomposition of a matrix A.
|
1736 |
+
Given A, two orthogonal (A real) or unitary (A complex) matrices U and V
|
1737 |
+
are calculated such that
|
1738 |
+
|
1739 |
+
A = U S V and U' U = 1 and V V' = 1
|
1740 |
+
|
1741 |
+
where S is a suitable shaped matrix whose off-diagonal elements are zero.
|
1742 |
+
Here ' denotes the hermitian transpose (i.e. transposition and complex
|
1743 |
+
conjugation). The diagonal elements of S are the singular values of A,
|
1744 |
+
i.e. the squareroots of the eigenvalues of A' A or A A'.
|
1745 |
+
|
1746 |
+
input:
|
1747 |
+
A : a real or complex matrix of shape (m, n)
|
1748 |
+
full_matrices : if true, U and V are of shape (m, m) and (n, n).
|
1749 |
+
if false, U and V are of shape (m, min(m, n)) and (min(m, n), n).
|
1750 |
+
compute_uv : if true, U and V are calculated. if false, only S is calculated.
|
1751 |
+
overwrite_a : if true, allows modification of A which may improve
|
1752 |
+
performance. if false, A is not modified.
|
1753 |
+
|
1754 |
+
output:
|
1755 |
+
U : an orthogonal or unitary matrix: U' U = 1. if full_matrices is true, U is of
|
1756 |
+
shape (m, m). ortherwise it is of shape (m, min(m, n)).
|
1757 |
+
|
1758 |
+
S : an array of length min(m, n) containing the singular values of A sorted by
|
1759 |
+
decreasing magnitude.
|
1760 |
+
|
1761 |
+
V : an orthogonal or unitary matrix: V V' = 1. if full_matrices is true, V is of
|
1762 |
+
shape (n, n). ortherwise it is of shape (min(m, n), n).
|
1763 |
+
|
1764 |
+
return value:
|
1765 |
+
|
1766 |
+
S if compute_uv is false
|
1767 |
+
(U, S, V) if compute_uv is true
|
1768 |
+
|
1769 |
+
overview of the matrices:
|
1770 |
+
|
1771 |
+
full_matrices true:
|
1772 |
+
A : m*n
|
1773 |
+
U : m*m U' U = 1
|
1774 |
+
S as matrix : m*n
|
1775 |
+
V : n*n V V' = 1
|
1776 |
+
|
1777 |
+
full_matrices false:
|
1778 |
+
A : m*n
|
1779 |
+
U : m*min(n,m) U' U = 1
|
1780 |
+
S as matrix : min(m,n)*min(m,n)
|
1781 |
+
V : min(m,n)*n V V' = 1
|
1782 |
+
|
1783 |
+
examples:
|
1784 |
+
|
1785 |
+
>>> from mpmath import mp
|
1786 |
+
>>> A = mp.matrix([[2, -2, -1], [3, 4, -2], [-2, -2, 0]])
|
1787 |
+
>>> S = mp.svd(A, compute_uv = False)
|
1788 |
+
>>> print(S)
|
1789 |
+
[6.0]
|
1790 |
+
[3.0]
|
1791 |
+
[1.0]
|
1792 |
+
|
1793 |
+
>>> U, S, V = mp.svd(A)
|
1794 |
+
>>> print(mp.chop(A - U * mp.diag(S) * V))
|
1795 |
+
[0.0 0.0 0.0]
|
1796 |
+
[0.0 0.0 0.0]
|
1797 |
+
[0.0 0.0 0.0]
|
1798 |
+
|
1799 |
+
see also: svd_r, svd_c
|
1800 |
+
"""
|
1801 |
+
|
1802 |
+
iscomplex = any(type(x) is ctx.mpc for x in A)
|
1803 |
+
|
1804 |
+
if iscomplex:
|
1805 |
+
return ctx.svd_c(A, full_matrices = full_matrices, compute_uv = compute_uv, overwrite_a = overwrite_a)
|
1806 |
+
else:
|
1807 |
+
return ctx.svd_r(A, full_matrices = full_matrices, compute_uv = compute_uv, overwrite_a = overwrite_a)
|
env-llmeval/lib/python3.10/site-packages/mpmath/rational.py
ADDED
@@ -0,0 +1,240 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import operator
|
2 |
+
import sys
|
3 |
+
from .libmp import int_types, mpf_hash, bitcount, from_man_exp, HASH_MODULUS
|
4 |
+
|
5 |
+
new = object.__new__
|
6 |
+
|
7 |
+
def create_reduced(p, q, _cache={}):
|
8 |
+
key = p, q
|
9 |
+
if key in _cache:
|
10 |
+
return _cache[key]
|
11 |
+
x, y = p, q
|
12 |
+
while y:
|
13 |
+
x, y = y, x % y
|
14 |
+
if x != 1:
|
15 |
+
p //= x
|
16 |
+
q //= x
|
17 |
+
v = new(mpq)
|
18 |
+
v._mpq_ = p, q
|
19 |
+
# Speedup integers, half-integers and other small fractions
|
20 |
+
if q <= 4 and abs(key[0]) < 100:
|
21 |
+
_cache[key] = v
|
22 |
+
return v
|
23 |
+
|
24 |
+
class mpq(object):
|
25 |
+
"""
|
26 |
+
Exact rational type, currently only intended for internal use.
|
27 |
+
"""
|
28 |
+
|
29 |
+
__slots__ = ["_mpq_"]
|
30 |
+
|
31 |
+
def __new__(cls, p, q=1):
|
32 |
+
if type(p) is tuple:
|
33 |
+
p, q = p
|
34 |
+
elif hasattr(p, '_mpq_'):
|
35 |
+
p, q = p._mpq_
|
36 |
+
return create_reduced(p, q)
|
37 |
+
|
38 |
+
def __repr__(s):
|
39 |
+
return "mpq(%s,%s)" % s._mpq_
|
40 |
+
|
41 |
+
def __str__(s):
|
42 |
+
return "(%s/%s)" % s._mpq_
|
43 |
+
|
44 |
+
def __int__(s):
|
45 |
+
a, b = s._mpq_
|
46 |
+
return a // b
|
47 |
+
|
48 |
+
def __nonzero__(s):
|
49 |
+
return bool(s._mpq_[0])
|
50 |
+
|
51 |
+
__bool__ = __nonzero__
|
52 |
+
|
53 |
+
def __hash__(s):
|
54 |
+
a, b = s._mpq_
|
55 |
+
if sys.version_info >= (3, 2):
|
56 |
+
inverse = pow(b, HASH_MODULUS-2, HASH_MODULUS)
|
57 |
+
if not inverse:
|
58 |
+
h = sys.hash_info.inf
|
59 |
+
else:
|
60 |
+
h = (abs(a) * inverse) % HASH_MODULUS
|
61 |
+
if a < 0: h = -h
|
62 |
+
if h == -1: h = -2
|
63 |
+
return h
|
64 |
+
else:
|
65 |
+
if b == 1:
|
66 |
+
return hash(a)
|
67 |
+
# Power of two: mpf compatible hash
|
68 |
+
if not (b & (b-1)):
|
69 |
+
return mpf_hash(from_man_exp(a, 1-bitcount(b)))
|
70 |
+
return hash((a,b))
|
71 |
+
|
72 |
+
def __eq__(s, t):
|
73 |
+
ttype = type(t)
|
74 |
+
if ttype is mpq:
|
75 |
+
return s._mpq_ == t._mpq_
|
76 |
+
if ttype in int_types:
|
77 |
+
a, b = s._mpq_
|
78 |
+
if b != 1:
|
79 |
+
return False
|
80 |
+
return a == t
|
81 |
+
return NotImplemented
|
82 |
+
|
83 |
+
def __ne__(s, t):
|
84 |
+
ttype = type(t)
|
85 |
+
if ttype is mpq:
|
86 |
+
return s._mpq_ != t._mpq_
|
87 |
+
if ttype in int_types:
|
88 |
+
a, b = s._mpq_
|
89 |
+
if b != 1:
|
90 |
+
return True
|
91 |
+
return a != t
|
92 |
+
return NotImplemented
|
93 |
+
|
94 |
+
def _cmp(s, t, op):
|
95 |
+
ttype = type(t)
|
96 |
+
if ttype in int_types:
|
97 |
+
a, b = s._mpq_
|
98 |
+
return op(a, t*b)
|
99 |
+
if ttype is mpq:
|
100 |
+
a, b = s._mpq_
|
101 |
+
c, d = t._mpq_
|
102 |
+
return op(a*d, b*c)
|
103 |
+
return NotImplementedError
|
104 |
+
|
105 |
+
def __lt__(s, t): return s._cmp(t, operator.lt)
|
106 |
+
def __le__(s, t): return s._cmp(t, operator.le)
|
107 |
+
def __gt__(s, t): return s._cmp(t, operator.gt)
|
108 |
+
def __ge__(s, t): return s._cmp(t, operator.ge)
|
109 |
+
|
110 |
+
def __abs__(s):
|
111 |
+
a, b = s._mpq_
|
112 |
+
if a >= 0:
|
113 |
+
return s
|
114 |
+
v = new(mpq)
|
115 |
+
v._mpq_ = -a, b
|
116 |
+
return v
|
117 |
+
|
118 |
+
def __neg__(s):
|
119 |
+
a, b = s._mpq_
|
120 |
+
v = new(mpq)
|
121 |
+
v._mpq_ = -a, b
|
122 |
+
return v
|
123 |
+
|
124 |
+
def __pos__(s):
|
125 |
+
return s
|
126 |
+
|
127 |
+
def __add__(s, t):
|
128 |
+
ttype = type(t)
|
129 |
+
if ttype is mpq:
|
130 |
+
a, b = s._mpq_
|
131 |
+
c, d = t._mpq_
|
132 |
+
return create_reduced(a*d+b*c, b*d)
|
133 |
+
if ttype in int_types:
|
134 |
+
a, b = s._mpq_
|
135 |
+
v = new(mpq)
|
136 |
+
v._mpq_ = a+b*t, b
|
137 |
+
return v
|
138 |
+
return NotImplemented
|
139 |
+
|
140 |
+
__radd__ = __add__
|
141 |
+
|
142 |
+
def __sub__(s, t):
|
143 |
+
ttype = type(t)
|
144 |
+
if ttype is mpq:
|
145 |
+
a, b = s._mpq_
|
146 |
+
c, d = t._mpq_
|
147 |
+
return create_reduced(a*d-b*c, b*d)
|
148 |
+
if ttype in int_types:
|
149 |
+
a, b = s._mpq_
|
150 |
+
v = new(mpq)
|
151 |
+
v._mpq_ = a-b*t, b
|
152 |
+
return v
|
153 |
+
return NotImplemented
|
154 |
+
|
155 |
+
def __rsub__(s, t):
|
156 |
+
ttype = type(t)
|
157 |
+
if ttype is mpq:
|
158 |
+
a, b = s._mpq_
|
159 |
+
c, d = t._mpq_
|
160 |
+
return create_reduced(b*c-a*d, b*d)
|
161 |
+
if ttype in int_types:
|
162 |
+
a, b = s._mpq_
|
163 |
+
v = new(mpq)
|
164 |
+
v._mpq_ = b*t-a, b
|
165 |
+
return v
|
166 |
+
return NotImplemented
|
167 |
+
|
168 |
+
def __mul__(s, t):
|
169 |
+
ttype = type(t)
|
170 |
+
if ttype is mpq:
|
171 |
+
a, b = s._mpq_
|
172 |
+
c, d = t._mpq_
|
173 |
+
return create_reduced(a*c, b*d)
|
174 |
+
if ttype in int_types:
|
175 |
+
a, b = s._mpq_
|
176 |
+
return create_reduced(a*t, b)
|
177 |
+
return NotImplemented
|
178 |
+
|
179 |
+
__rmul__ = __mul__
|
180 |
+
|
181 |
+
def __div__(s, t):
|
182 |
+
ttype = type(t)
|
183 |
+
if ttype is mpq:
|
184 |
+
a, b = s._mpq_
|
185 |
+
c, d = t._mpq_
|
186 |
+
return create_reduced(a*d, b*c)
|
187 |
+
if ttype in int_types:
|
188 |
+
a, b = s._mpq_
|
189 |
+
return create_reduced(a, b*t)
|
190 |
+
return NotImplemented
|
191 |
+
|
192 |
+
def __rdiv__(s, t):
|
193 |
+
ttype = type(t)
|
194 |
+
if ttype is mpq:
|
195 |
+
a, b = s._mpq_
|
196 |
+
c, d = t._mpq_
|
197 |
+
return create_reduced(b*c, a*d)
|
198 |
+
if ttype in int_types:
|
199 |
+
a, b = s._mpq_
|
200 |
+
return create_reduced(b*t, a)
|
201 |
+
return NotImplemented
|
202 |
+
|
203 |
+
def __pow__(s, t):
|
204 |
+
ttype = type(t)
|
205 |
+
if ttype in int_types:
|
206 |
+
a, b = s._mpq_
|
207 |
+
if t:
|
208 |
+
if t < 0:
|
209 |
+
a, b, t = b, a, -t
|
210 |
+
v = new(mpq)
|
211 |
+
v._mpq_ = a**t, b**t
|
212 |
+
return v
|
213 |
+
raise ZeroDivisionError
|
214 |
+
return NotImplemented
|
215 |
+
|
216 |
+
|
217 |
+
mpq_1 = mpq((1,1))
|
218 |
+
mpq_0 = mpq((0,1))
|
219 |
+
mpq_1_2 = mpq((1,2))
|
220 |
+
mpq_3_2 = mpq((3,2))
|
221 |
+
mpq_1_4 = mpq((1,4))
|
222 |
+
mpq_1_16 = mpq((1,16))
|
223 |
+
mpq_3_16 = mpq((3,16))
|
224 |
+
mpq_5_2 = mpq((5,2))
|
225 |
+
mpq_3_4 = mpq((3,4))
|
226 |
+
mpq_7_4 = mpq((7,4))
|
227 |
+
mpq_5_4 = mpq((5,4))
|
228 |
+
|
229 |
+
|
230 |
+
# Register with "numbers" ABC
|
231 |
+
# We do not subclass, hence we do not use the @abstractmethod checks. While
|
232 |
+
# this is less invasive it may turn out that we do not actually support
|
233 |
+
# parts of the expected interfaces. See
|
234 |
+
# http://docs.python.org/2/library/numbers.html for list of abstract
|
235 |
+
# methods.
|
236 |
+
try:
|
237 |
+
import numbers
|
238 |
+
numbers.Rational.register(mpq)
|
239 |
+
except ImportError:
|
240 |
+
pass
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__init__.py
ADDED
File without changes
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (177 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/extratest_zeta.cpython-310.pyc
ADDED
Binary file (968 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_basic_ops.cpython-310.pyc
ADDED
Binary file (14 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_bitwise.cpython-310.pyc
ADDED
Binary file (6.66 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_calculus.cpython-310.pyc
ADDED
Binary file (7.35 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_diff.cpython-310.pyc
ADDED
Binary file (3.64 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_division.cpython-310.pyc
ADDED
Binary file (4.45 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_eigen.cpython-310.pyc
ADDED
Binary file (3.58 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_eigen_symmetric.cpython-310.pyc
ADDED
Binary file (8.96 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_fp.cpython-310.pyc
ADDED
Binary file (53.4 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_functions.cpython-310.pyc
ADDED
Binary file (31.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_functions2.cpython-310.pyc
ADDED
Binary file (66.8 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_hp.cpython-310.pyc
ADDED
Binary file (8.72 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_identify.cpython-310.pyc
ADDED
Binary file (1.06 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_interval.cpython-310.pyc
ADDED
Binary file (16.3 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_levin.cpython-310.pyc
ADDED
Binary file (5.96 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_matrices.cpython-310.pyc
ADDED
Binary file (8.88 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_mpmath.cpython-310.pyc
ADDED
Binary file (461 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_ode.cpython-310.pyc
ADDED
Binary file (1.63 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_pickle.cpython-310.pyc
ADDED
Binary file (711 Bytes). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_power.cpython-310.pyc
ADDED
Binary file (4.35 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_quad.cpython-310.pyc
ADDED
Binary file (8.62 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_rootfinding.cpython-310.pyc
ADDED
Binary file (5.7 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_special.cpython-310.pyc
ADDED
Binary file (2.88 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_trig.cpython-310.pyc
ADDED
Binary file (4.09 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/test_visualization.cpython-310.pyc
ADDED
Binary file (1.43 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/__pycache__/torture.cpython-310.pyc
ADDED
Binary file (8.18 kB). View file
|
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/extratest_gamma.py
ADDED
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from mpmath import *
|
2 |
+
from mpmath.libmp import ifac
|
3 |
+
|
4 |
+
import sys
|
5 |
+
if "-dps" in sys.argv:
|
6 |
+
maxdps = int(sys.argv[sys.argv.index("-dps")+1])
|
7 |
+
else:
|
8 |
+
maxdps = 1000
|
9 |
+
|
10 |
+
raise_ = "-raise" in sys.argv
|
11 |
+
|
12 |
+
errcount = 0
|
13 |
+
|
14 |
+
def check(name, func, z, y):
|
15 |
+
global errcount
|
16 |
+
try:
|
17 |
+
x = func(z)
|
18 |
+
except:
|
19 |
+
errcount += 1
|
20 |
+
if raise_:
|
21 |
+
raise
|
22 |
+
print()
|
23 |
+
print(name)
|
24 |
+
print("EXCEPTION")
|
25 |
+
import traceback
|
26 |
+
traceback.print_tb(sys.exc_info()[2])
|
27 |
+
print()
|
28 |
+
return
|
29 |
+
xre = x.real
|
30 |
+
xim = x.imag
|
31 |
+
yre = y.real
|
32 |
+
yim = y.imag
|
33 |
+
tol = eps*8
|
34 |
+
err = 0
|
35 |
+
if abs(xre-yre) > abs(yre)*tol:
|
36 |
+
err = 1
|
37 |
+
print()
|
38 |
+
print("Error! %s (re = %s, wanted %s, err=%s)" % (name, nstr(xre,10), nstr(yre,10), nstr(abs(xre-yre))))
|
39 |
+
errcount += 1
|
40 |
+
if raise_:
|
41 |
+
raise SystemExit
|
42 |
+
if abs(xim-yim) > abs(yim)*tol:
|
43 |
+
err = 1
|
44 |
+
print()
|
45 |
+
print("Error! %s (im = %s, wanted %s, err=%s)" % (name, nstr(xim,10), nstr(yim,10), nstr(abs(xim-yim))))
|
46 |
+
errcount += 1
|
47 |
+
if raise_:
|
48 |
+
raise SystemExit
|
49 |
+
if not err:
|
50 |
+
sys.stdout.write("%s ok; " % name)
|
51 |
+
|
52 |
+
def testcase(case):
|
53 |
+
z, result = case
|
54 |
+
print("Testing z =", z)
|
55 |
+
mp.dps = 1010
|
56 |
+
z = eval(z)
|
57 |
+
mp.dps = maxdps + 50
|
58 |
+
if result is None:
|
59 |
+
gamma_val = gamma(z)
|
60 |
+
loggamma_val = loggamma(z)
|
61 |
+
factorial_val = factorial(z)
|
62 |
+
rgamma_val = rgamma(z)
|
63 |
+
else:
|
64 |
+
loggamma_val = eval(result)
|
65 |
+
gamma_val = exp(loggamma_val)
|
66 |
+
factorial_val = z * gamma_val
|
67 |
+
rgamma_val = 1/gamma_val
|
68 |
+
for dps in [5, 10, 15, 25, 40, 60, 90, 120, 250, 600, 1000, 1800, 3600]:
|
69 |
+
if dps > maxdps:
|
70 |
+
break
|
71 |
+
mp.dps = dps
|
72 |
+
print("dps = %s" % dps)
|
73 |
+
check("gamma", gamma, z, gamma_val)
|
74 |
+
check("rgamma", rgamma, z, rgamma_val)
|
75 |
+
check("loggamma", loggamma, z, loggamma_val)
|
76 |
+
check("factorial", factorial, z, factorial_val)
|
77 |
+
print()
|
78 |
+
mp.dps = 15
|
79 |
+
|
80 |
+
testcases = []
|
81 |
+
|
82 |
+
# Basic values
|
83 |
+
for n in list(range(1,200)) + list(range(201,2000,17)):
|
84 |
+
testcases.append(["%s" % n, None])
|
85 |
+
for n in range(-200,200):
|
86 |
+
testcases.append(["%s+0.5" % n, None])
|
87 |
+
testcases.append(["%s+0.37" % n, None])
|
88 |
+
|
89 |
+
testcases += [\
|
90 |
+
["(0.1+1j)", None],
|
91 |
+
["(-0.1+1j)", None],
|
92 |
+
["(0.1-1j)", None],
|
93 |
+
["(-0.1-1j)", None],
|
94 |
+
["10j", None],
|
95 |
+
["-10j", None],
|
96 |
+
["100j", None],
|
97 |
+
["10000j", None],
|
98 |
+
["-10000000j", None],
|
99 |
+
["(10**100)*j", None],
|
100 |
+
["125+(10**100)*j", None],
|
101 |
+
["-125+(10**100)*j", None],
|
102 |
+
["(10**10)*(1+j)", None],
|
103 |
+
["(10**10)*(-1+j)", None],
|
104 |
+
["(10**100)*(1+j)", None],
|
105 |
+
["(10**100)*(-1+j)", None],
|
106 |
+
["(1.5-1j)", None],
|
107 |
+
["(6+4j)", None],
|
108 |
+
["(4+1j)", None],
|
109 |
+
["(3.5+2j)", None],
|
110 |
+
["(1.5-1j)", None],
|
111 |
+
["(-6-4j)", None],
|
112 |
+
["(-2-3j)", None],
|
113 |
+
["(-2.5-2j)", None],
|
114 |
+
["(4+1j)", None],
|
115 |
+
["(3+3j)", None],
|
116 |
+
["(2-2j)", None],
|
117 |
+
["1", "0"],
|
118 |
+
["2", "0"],
|
119 |
+
["3", "log(2)"],
|
120 |
+
["4", "log(6)"],
|
121 |
+
["5", "log(24)"],
|
122 |
+
["0.5", "log(pi)/2"],
|
123 |
+
["1.5", "log(sqrt(pi)/2)"],
|
124 |
+
["2.5", "log(3*sqrt(pi)/4)"],
|
125 |
+
["mpf('0.37')", None],
|
126 |
+
["0.25", "log(sqrt(2*sqrt(2*pi**3)/agm(1,sqrt(2))))"],
|
127 |
+
["-0.4", None],
|
128 |
+
["mpf('-1.9')", None],
|
129 |
+
["mpf('12.8')", None],
|
130 |
+
["mpf('33.7')", None],
|
131 |
+
["mpf('95.2')", None],
|
132 |
+
["mpf('160.3')", None],
|
133 |
+
["mpf('2057.8')", None],
|
134 |
+
["25", "log(ifac(24))"],
|
135 |
+
["80", "log(ifac(79))"],
|
136 |
+
["500", "log(ifac(500-1))"],
|
137 |
+
["8000", "log(ifac(8000-1))"],
|
138 |
+
["8000.5", None],
|
139 |
+
["mpf('8000.1')", None],
|
140 |
+
["mpf('1.37e10')", None],
|
141 |
+
["mpf('1.37e10')*(1+j)", None],
|
142 |
+
["mpf('1.37e10')*(-1+j)", None],
|
143 |
+
["mpf('1.37e10')*(-1-j)", None],
|
144 |
+
["mpf('1.37e10')*(-1+j)", None],
|
145 |
+
["mpf('1.37e100')", None],
|
146 |
+
["mpf('1.37e100')*(1+j)", None],
|
147 |
+
["mpf('1.37e100')*(-1+j)", None],
|
148 |
+
["mpf('1.37e100')*(-1-j)", None],
|
149 |
+
["mpf('1.37e100')*(-1+j)", None],
|
150 |
+
["3+4j",
|
151 |
+
"mpc('"
|
152 |
+
"-1.7566267846037841105306041816232757851567066070613445016197619371316057169"
|
153 |
+
"4723618263960834804618463052988607348289672535780644470689771115236512106002"
|
154 |
+
"5970873471563240537307638968509556191696167970488390423963867031934333890838"
|
155 |
+
"8009531786948197210025029725361069435208930363494971027388382086721660805397"
|
156 |
+
"9163230643216054580167976201709951509519218635460317367338612500626714783631"
|
157 |
+
"7498317478048447525674016344322545858832610325861086336204591943822302971823"
|
158 |
+
"5161814175530618223688296232894588415495615809337292518431903058265147109853"
|
159 |
+
"1710568942184987827643886816200452860853873815413367529829631430146227470517"
|
160 |
+
"6579967222200868632179482214312673161276976117132204633283806161971389519137"
|
161 |
+
"1243359764435612951384238091232760634271570950240717650166551484551654327989"
|
162 |
+
"9360285030081716934130446150245110557038117075172576825490035434069388648124"
|
163 |
+
"6678152254554001586736120762641422590778766100376515737713938521275749049949"
|
164 |
+
"1284143906816424244705094759339932733567910991920631339597278805393743140853"
|
165 |
+
"391550313363278558195609260225928','"
|
166 |
+
"4.74266443803465792819488940755002274088830335171164611359052405215840070271"
|
167 |
+
"5906813009373171139767051863542508136875688550817670379002790304870822775498"
|
168 |
+
"2809996675877564504192565392367259119610438951593128982646945990372179860613"
|
169 |
+
"4294436498090428077839141927485901735557543641049637962003652638924845391650"
|
170 |
+
"9546290137755550107224907606529385248390667634297183361902055842228798984200"
|
171 |
+
"9591180450211798341715874477629099687609819466457990642030707080894518168924"
|
172 |
+
"6805549314043258530272479246115112769957368212585759640878745385160943755234"
|
173 |
+
"9398036774908108204370323896757543121853650025529763655312360354244898913463"
|
174 |
+
"7115955702828838923393113618205074162812089732064414530813087483533203244056"
|
175 |
+
"0546577484241423134079056537777170351934430586103623577814746004431994179990"
|
176 |
+
"5318522939077992613855205801498201930221975721246498720895122345420698451980"
|
177 |
+
"0051215797310305885845964334761831751370672996984756815410977750799748813563"
|
178 |
+
"8784405288158432214886648743541773208808731479748217023665577802702269468013"
|
179 |
+
"673719173759245720489020315779001')"],
|
180 |
+
]
|
181 |
+
|
182 |
+
for z in [4, 14, 34, 64]:
|
183 |
+
testcases.append(["(2+j)*%s/3" % z, None])
|
184 |
+
testcases.append(["(-2+j)*%s/3" % z, None])
|
185 |
+
testcases.append(["(1+2*j)*%s/3" % z, None])
|
186 |
+
testcases.append(["(2-j)*%s/3" % z, None])
|
187 |
+
testcases.append(["(20+j)*%s/3" % z, None])
|
188 |
+
testcases.append(["(-20+j)*%s/3" % z, None])
|
189 |
+
testcases.append(["(1+20*j)*%s/3" % z, None])
|
190 |
+
testcases.append(["(20-j)*%s/3" % z, None])
|
191 |
+
testcases.append(["(200+j)*%s/3" % z, None])
|
192 |
+
testcases.append(["(-200+j)*%s/3" % z, None])
|
193 |
+
testcases.append(["(1+200*j)*%s/3" % z, None])
|
194 |
+
testcases.append(["(200-j)*%s/3" % z, None])
|
195 |
+
|
196 |
+
# Poles
|
197 |
+
for n in [0,1,2,3,4,25,-1,-2,-3,-4,-20,-21,-50,-51,-200,-201,-20000,-20001]:
|
198 |
+
for t in ['1e-5', '1e-20', '1e-100', '1e-10000']:
|
199 |
+
testcases.append(["fadd(%s,'%s',exact=True)" % (n, t), None])
|
200 |
+
testcases.append(["fsub(%s,'%s',exact=True)" % (n, t), None])
|
201 |
+
testcases.append(["fadd(%s,'%sj',exact=True)" % (n, t), None])
|
202 |
+
testcases.append(["fsub(%s,'%sj',exact=True)" % (n, t), None])
|
203 |
+
|
204 |
+
if __name__ == "__main__":
|
205 |
+
from timeit import default_timer as clock
|
206 |
+
tot_time = 0.0
|
207 |
+
for case in testcases:
|
208 |
+
t1 = clock()
|
209 |
+
testcase(case)
|
210 |
+
t2 = clock()
|
211 |
+
print("Test time:", t2-t1)
|
212 |
+
print()
|
213 |
+
tot_time += (t2-t1)
|
214 |
+
print("Total time:", tot_time)
|
215 |
+
print("Errors:", errcount)
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/extratest_zeta.py
ADDED
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from mpmath import zetazero
|
2 |
+
from timeit import default_timer as clock
|
3 |
+
|
4 |
+
def test_zetazero():
|
5 |
+
cases = [\
|
6 |
+
(399999999, 156762524.6750591511),
|
7 |
+
(241389216, 97490234.2276711795),
|
8 |
+
(526196239, 202950727.691229534),
|
9 |
+
(542964976, 209039046.578535272),
|
10 |
+
(1048449112, 388858885.231056486),
|
11 |
+
(1048449113, 388858885.384337406),
|
12 |
+
(1048449114, 388858886.002285122),
|
13 |
+
(1048449115, 388858886.00239369),
|
14 |
+
(1048449116, 388858886.690745053)
|
15 |
+
]
|
16 |
+
for n, v in cases:
|
17 |
+
print(n, v)
|
18 |
+
t1 = clock()
|
19 |
+
ok = zetazero(n).ae(complex(0.5,v))
|
20 |
+
t2 = clock()
|
21 |
+
print("ok =", ok, ("(time = %s)" % round(t2-t1,3)))
|
22 |
+
print("Now computing two huge zeros (this may take hours)")
|
23 |
+
print("Computing zetazero(8637740722917)")
|
24 |
+
ok = zetazero(8637740722917).ae(complex(0.5,2124447368584.39296466152))
|
25 |
+
print("ok =", ok)
|
26 |
+
ok = zetazero(8637740722918).ae(complex(0.5,2124447368584.39298170604))
|
27 |
+
print("ok =", ok)
|
28 |
+
|
29 |
+
if __name__ == "__main__":
|
30 |
+
test_zetazero()
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/runtests.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/env python
|
2 |
+
|
3 |
+
"""
|
4 |
+
python runtests.py -py
|
5 |
+
Use py.test to run tests (more useful for debugging)
|
6 |
+
|
7 |
+
python runtests.py -coverage
|
8 |
+
Generate test coverage report. Statistics are written to /tmp
|
9 |
+
|
10 |
+
python runtests.py -profile
|
11 |
+
Generate profile stats (this is much slower)
|
12 |
+
|
13 |
+
python runtests.py -nogmpy
|
14 |
+
Run tests without using GMPY even if it exists
|
15 |
+
|
16 |
+
python runtests.py -strict
|
17 |
+
Enforce extra tests in normalize()
|
18 |
+
|
19 |
+
python runtests.py -local
|
20 |
+
Insert '../..' at the beginning of sys.path to use local mpmath
|
21 |
+
|
22 |
+
python runtests.py -skip ...
|
23 |
+
Skip tests from the listed modules
|
24 |
+
|
25 |
+
Additional arguments are used to filter the tests to run. Only files that have
|
26 |
+
one of the arguments in their name are executed.
|
27 |
+
|
28 |
+
"""
|
29 |
+
|
30 |
+
import sys, os, traceback
|
31 |
+
|
32 |
+
profile = False
|
33 |
+
if "-profile" in sys.argv:
|
34 |
+
sys.argv.remove('-profile')
|
35 |
+
profile = True
|
36 |
+
|
37 |
+
coverage = False
|
38 |
+
if "-coverage" in sys.argv:
|
39 |
+
sys.argv.remove('-coverage')
|
40 |
+
coverage = True
|
41 |
+
|
42 |
+
if "-nogmpy" in sys.argv:
|
43 |
+
sys.argv.remove('-nogmpy')
|
44 |
+
os.environ['MPMATH_NOGMPY'] = 'Y'
|
45 |
+
|
46 |
+
if "-strict" in sys.argv:
|
47 |
+
sys.argv.remove('-strict')
|
48 |
+
os.environ['MPMATH_STRICT'] = 'Y'
|
49 |
+
|
50 |
+
if "-local" in sys.argv:
|
51 |
+
sys.argv.remove('-local')
|
52 |
+
importdir = os.path.abspath(os.path.join(os.path.dirname(sys.argv[0]),
|
53 |
+
'../..'))
|
54 |
+
else:
|
55 |
+
importdir = ''
|
56 |
+
|
57 |
+
# TODO: add a flag for this
|
58 |
+
testdir = ''
|
59 |
+
|
60 |
+
def testit(importdir='', testdir='', exit_on_fail=False):
|
61 |
+
"""Run all tests in testdir while importing from importdir."""
|
62 |
+
if importdir:
|
63 |
+
sys.path.insert(1, importdir)
|
64 |
+
if testdir:
|
65 |
+
sys.path.insert(1, testdir)
|
66 |
+
import os.path
|
67 |
+
import mpmath
|
68 |
+
print("mpmath imported from %s" % os.path.dirname(mpmath.__file__))
|
69 |
+
print("mpmath backend: %s" % mpmath.libmp.backend.BACKEND)
|
70 |
+
print("mpmath mp class: %s" % repr(mpmath.mp))
|
71 |
+
print("mpmath version: %s" % mpmath.__version__)
|
72 |
+
print("Python version: %s" % sys.version)
|
73 |
+
print("")
|
74 |
+
if "-py" in sys.argv:
|
75 |
+
sys.argv.remove('-py')
|
76 |
+
import py
|
77 |
+
py.test.cmdline.main()
|
78 |
+
else:
|
79 |
+
import glob
|
80 |
+
from timeit import default_timer as clock
|
81 |
+
modules = []
|
82 |
+
args = sys.argv[1:]
|
83 |
+
excluded = []
|
84 |
+
if '-skip' in args:
|
85 |
+
excluded = args[args.index('-skip')+1:]
|
86 |
+
args = args[:args.index('-skip')]
|
87 |
+
# search for tests in directory of this file if not otherwise specified
|
88 |
+
if not testdir:
|
89 |
+
pattern = os.path.dirname(sys.argv[0])
|
90 |
+
else:
|
91 |
+
pattern = testdir
|
92 |
+
if pattern:
|
93 |
+
pattern += '/'
|
94 |
+
pattern += 'test*.py'
|
95 |
+
# look for tests (respecting specified filter)
|
96 |
+
for f in glob.glob(pattern):
|
97 |
+
name = os.path.splitext(os.path.basename(f))[0]
|
98 |
+
# If run as a script, only run tests given as args, if any are given
|
99 |
+
if args and __name__ == "__main__":
|
100 |
+
ok = False
|
101 |
+
for arg in args:
|
102 |
+
if arg in name:
|
103 |
+
ok = True
|
104 |
+
break
|
105 |
+
if not ok:
|
106 |
+
continue
|
107 |
+
elif name in excluded:
|
108 |
+
continue
|
109 |
+
module = __import__(name)
|
110 |
+
priority = module.__dict__.get('priority', 100)
|
111 |
+
if priority == 666:
|
112 |
+
modules = [[priority, name, module]]
|
113 |
+
break
|
114 |
+
modules.append([priority, name, module])
|
115 |
+
# execute tests
|
116 |
+
modules.sort()
|
117 |
+
tstart = clock()
|
118 |
+
for priority, name, module in modules:
|
119 |
+
print(name)
|
120 |
+
for f in sorted(module.__dict__.keys()):
|
121 |
+
if f.startswith('test_'):
|
122 |
+
if coverage and ('numpy' in f):
|
123 |
+
continue
|
124 |
+
sys.stdout.write(" " + f[5:].ljust(25) + " ")
|
125 |
+
t1 = clock()
|
126 |
+
try:
|
127 |
+
module.__dict__[f]()
|
128 |
+
except:
|
129 |
+
etype, evalue, trb = sys.exc_info()
|
130 |
+
if etype in (KeyboardInterrupt, SystemExit):
|
131 |
+
raise
|
132 |
+
print("")
|
133 |
+
print("TEST FAILED!")
|
134 |
+
print("")
|
135 |
+
traceback.print_exc()
|
136 |
+
if exit_on_fail:
|
137 |
+
return
|
138 |
+
t2 = clock()
|
139 |
+
print("ok " + " " + ("%.7f" % (t2-t1)) + " s")
|
140 |
+
tend = clock()
|
141 |
+
print("")
|
142 |
+
print("finished tests in " + ("%.2f" % (tend-tstart)) + " seconds")
|
143 |
+
# clean sys.path
|
144 |
+
if importdir:
|
145 |
+
sys.path.remove(importdir)
|
146 |
+
if testdir:
|
147 |
+
sys.path.remove(testdir)
|
148 |
+
|
149 |
+
if __name__ == '__main__':
|
150 |
+
if profile:
|
151 |
+
import cProfile
|
152 |
+
cProfile.run("testit('%s', '%s')" % (importdir, testdir), sort=1)
|
153 |
+
elif coverage:
|
154 |
+
import trace
|
155 |
+
tracer = trace.Trace(ignoredirs=[sys.prefix, sys.exec_prefix],
|
156 |
+
trace=0, count=1)
|
157 |
+
tracer.run('testit(importdir, testdir)')
|
158 |
+
r = tracer.results()
|
159 |
+
r.write_results(show_missing=True, summary=True, coverdir="/tmp")
|
160 |
+
else:
|
161 |
+
testit(importdir, testdir)
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_basic_ops.py
ADDED
@@ -0,0 +1,451 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import mpmath
|
2 |
+
from mpmath import *
|
3 |
+
from mpmath.libmp import *
|
4 |
+
import random
|
5 |
+
import sys
|
6 |
+
|
7 |
+
try:
|
8 |
+
long = long
|
9 |
+
except NameError:
|
10 |
+
long = int
|
11 |
+
|
12 |
+
def test_type_compare():
|
13 |
+
assert mpf(2) == mpc(2,0)
|
14 |
+
assert mpf(0) == mpc(0)
|
15 |
+
assert mpf(2) != mpc(2, 0.00001)
|
16 |
+
assert mpf(2) == 2.0
|
17 |
+
assert mpf(2) != 3.0
|
18 |
+
assert mpf(2) == 2
|
19 |
+
assert mpf(2) != '2.0'
|
20 |
+
assert mpc(2) != '2.0'
|
21 |
+
|
22 |
+
def test_add():
|
23 |
+
assert mpf(2.5) + mpf(3) == 5.5
|
24 |
+
assert mpf(2.5) + 3 == 5.5
|
25 |
+
assert mpf(2.5) + 3.0 == 5.5
|
26 |
+
assert 3 + mpf(2.5) == 5.5
|
27 |
+
assert 3.0 + mpf(2.5) == 5.5
|
28 |
+
assert (3+0j) + mpf(2.5) == 5.5
|
29 |
+
assert mpc(2.5) + mpf(3) == 5.5
|
30 |
+
assert mpc(2.5) + 3 == 5.5
|
31 |
+
assert mpc(2.5) + 3.0 == 5.5
|
32 |
+
assert mpc(2.5) + (3+0j) == 5.5
|
33 |
+
assert 3 + mpc(2.5) == 5.5
|
34 |
+
assert 3.0 + mpc(2.5) == 5.5
|
35 |
+
assert (3+0j) + mpc(2.5) == 5.5
|
36 |
+
|
37 |
+
def test_sub():
|
38 |
+
assert mpf(2.5) - mpf(3) == -0.5
|
39 |
+
assert mpf(2.5) - 3 == -0.5
|
40 |
+
assert mpf(2.5) - 3.0 == -0.5
|
41 |
+
assert 3 - mpf(2.5) == 0.5
|
42 |
+
assert 3.0 - mpf(2.5) == 0.5
|
43 |
+
assert (3+0j) - mpf(2.5) == 0.5
|
44 |
+
assert mpc(2.5) - mpf(3) == -0.5
|
45 |
+
assert mpc(2.5) - 3 == -0.5
|
46 |
+
assert mpc(2.5) - 3.0 == -0.5
|
47 |
+
assert mpc(2.5) - (3+0j) == -0.5
|
48 |
+
assert 3 - mpc(2.5) == 0.5
|
49 |
+
assert 3.0 - mpc(2.5) == 0.5
|
50 |
+
assert (3+0j) - mpc(2.5) == 0.5
|
51 |
+
|
52 |
+
def test_mul():
|
53 |
+
assert mpf(2.5) * mpf(3) == 7.5
|
54 |
+
assert mpf(2.5) * 3 == 7.5
|
55 |
+
assert mpf(2.5) * 3.0 == 7.5
|
56 |
+
assert 3 * mpf(2.5) == 7.5
|
57 |
+
assert 3.0 * mpf(2.5) == 7.5
|
58 |
+
assert (3+0j) * mpf(2.5) == 7.5
|
59 |
+
assert mpc(2.5) * mpf(3) == 7.5
|
60 |
+
assert mpc(2.5) * 3 == 7.5
|
61 |
+
assert mpc(2.5) * 3.0 == 7.5
|
62 |
+
assert mpc(2.5) * (3+0j) == 7.5
|
63 |
+
assert 3 * mpc(2.5) == 7.5
|
64 |
+
assert 3.0 * mpc(2.5) == 7.5
|
65 |
+
assert (3+0j) * mpc(2.5) == 7.5
|
66 |
+
|
67 |
+
def test_div():
|
68 |
+
assert mpf(6) / mpf(3) == 2.0
|
69 |
+
assert mpf(6) / 3 == 2.0
|
70 |
+
assert mpf(6) / 3.0 == 2.0
|
71 |
+
assert 6 / mpf(3) == 2.0
|
72 |
+
assert 6.0 / mpf(3) == 2.0
|
73 |
+
assert (6+0j) / mpf(3.0) == 2.0
|
74 |
+
assert mpc(6) / mpf(3) == 2.0
|
75 |
+
assert mpc(6) / 3 == 2.0
|
76 |
+
assert mpc(6) / 3.0 == 2.0
|
77 |
+
assert mpc(6) / (3+0j) == 2.0
|
78 |
+
assert 6 / mpc(3) == 2.0
|
79 |
+
assert 6.0 / mpc(3) == 2.0
|
80 |
+
assert (6+0j) / mpc(3) == 2.0
|
81 |
+
|
82 |
+
def test_pow():
|
83 |
+
assert mpf(6) ** mpf(3) == 216.0
|
84 |
+
assert mpf(6) ** 3 == 216.0
|
85 |
+
assert mpf(6) ** 3.0 == 216.0
|
86 |
+
assert 6 ** mpf(3) == 216.0
|
87 |
+
assert 6.0 ** mpf(3) == 216.0
|
88 |
+
assert (6+0j) ** mpf(3.0) == 216.0
|
89 |
+
assert mpc(6) ** mpf(3) == 216.0
|
90 |
+
assert mpc(6) ** 3 == 216.0
|
91 |
+
assert mpc(6) ** 3.0 == 216.0
|
92 |
+
assert mpc(6) ** (3+0j) == 216.0
|
93 |
+
assert 6 ** mpc(3) == 216.0
|
94 |
+
assert 6.0 ** mpc(3) == 216.0
|
95 |
+
assert (6+0j) ** mpc(3) == 216.0
|
96 |
+
|
97 |
+
def test_mixed_misc():
|
98 |
+
assert 1 + mpf(3) == mpf(3) + 1 == 4
|
99 |
+
assert 1 - mpf(3) == -(mpf(3) - 1) == -2
|
100 |
+
assert 3 * mpf(2) == mpf(2) * 3 == 6
|
101 |
+
assert 6 / mpf(2) == mpf(6) / 2 == 3
|
102 |
+
assert 1.0 + mpf(3) == mpf(3) + 1.0 == 4
|
103 |
+
assert 1.0 - mpf(3) == -(mpf(3) - 1.0) == -2
|
104 |
+
assert 3.0 * mpf(2) == mpf(2) * 3.0 == 6
|
105 |
+
assert 6.0 / mpf(2) == mpf(6) / 2.0 == 3
|
106 |
+
|
107 |
+
def test_add_misc():
|
108 |
+
mp.dps = 15
|
109 |
+
assert mpf(4) + mpf(-70) == -66
|
110 |
+
assert mpf(1) + mpf(1.1)/80 == 1 + 1.1/80
|
111 |
+
assert mpf((1, 10000000000)) + mpf(3) == mpf((1, 10000000000))
|
112 |
+
assert mpf(3) + mpf((1, 10000000000)) == mpf((1, 10000000000))
|
113 |
+
assert mpf((1, -10000000000)) + mpf(3) == mpf(3)
|
114 |
+
assert mpf(3) + mpf((1, -10000000000)) == mpf(3)
|
115 |
+
assert mpf(1) + 1e-15 != 1
|
116 |
+
assert mpf(1) + 1e-20 == 1
|
117 |
+
assert mpf(1.07e-22) + 0 == mpf(1.07e-22)
|
118 |
+
assert mpf(0) + mpf(1.07e-22) == mpf(1.07e-22)
|
119 |
+
|
120 |
+
def test_complex_misc():
|
121 |
+
# many more tests needed
|
122 |
+
assert 1 + mpc(2) == 3
|
123 |
+
assert not mpc(2).ae(2 + 1e-13)
|
124 |
+
assert mpc(2+1e-15j).ae(2)
|
125 |
+
|
126 |
+
def test_complex_zeros():
|
127 |
+
for a in [0,2]:
|
128 |
+
for b in [0,3]:
|
129 |
+
for c in [0,4]:
|
130 |
+
for d in [0,5]:
|
131 |
+
assert mpc(a,b)*mpc(c,d) == complex(a,b)*complex(c,d)
|
132 |
+
|
133 |
+
def test_hash():
|
134 |
+
for i in range(-256, 256):
|
135 |
+
assert hash(mpf(i)) == hash(i)
|
136 |
+
assert hash(mpf(0.5)) == hash(0.5)
|
137 |
+
assert hash(mpc(2,3)) == hash(2+3j)
|
138 |
+
# Check that this doesn't fail
|
139 |
+
assert hash(inf)
|
140 |
+
# Check that overflow doesn't assign equal hashes to large numbers
|
141 |
+
assert hash(mpf('1e1000')) != hash('1e10000')
|
142 |
+
assert hash(mpc(100,'1e1000')) != hash(mpc(200,'1e1000'))
|
143 |
+
from mpmath.rational import mpq
|
144 |
+
assert hash(mp.mpq(1,3))
|
145 |
+
assert hash(mp.mpq(0,1)) == 0
|
146 |
+
assert hash(mp.mpq(-1,1)) == hash(-1)
|
147 |
+
assert hash(mp.mpq(1,1)) == hash(1)
|
148 |
+
assert hash(mp.mpq(5,1)) == hash(5)
|
149 |
+
assert hash(mp.mpq(1,2)) == hash(0.5)
|
150 |
+
if sys.version_info >= (3, 2):
|
151 |
+
assert hash(mpf(1)*2**2000) == hash(2**2000)
|
152 |
+
assert hash(mpf(1)/2**2000) == hash(mpq(1,2**2000))
|
153 |
+
|
154 |
+
# Advanced rounding test
|
155 |
+
def test_add_rounding():
|
156 |
+
mp.dps = 15
|
157 |
+
a = from_float(1e-50)
|
158 |
+
assert mpf_sub(mpf_add(fone, a, 53, round_up), fone, 53, round_up) == from_float(2.2204460492503131e-16)
|
159 |
+
assert mpf_sub(fone, a, 53, round_up) == fone
|
160 |
+
assert mpf_sub(fone, mpf_sub(fone, a, 53, round_down), 53, round_down) == from_float(1.1102230246251565e-16)
|
161 |
+
assert mpf_add(fone, a, 53, round_down) == fone
|
162 |
+
|
163 |
+
def test_almost_equal():
|
164 |
+
assert mpf(1.2).ae(mpf(1.20000001), 1e-7)
|
165 |
+
assert not mpf(1.2).ae(mpf(1.20000001), 1e-9)
|
166 |
+
assert not mpf(-0.7818314824680298).ae(mpf(-0.774695868667929))
|
167 |
+
|
168 |
+
def test_arithmetic_functions():
|
169 |
+
import operator
|
170 |
+
ops = [(operator.add, fadd), (operator.sub, fsub), (operator.mul, fmul),
|
171 |
+
(operator.truediv, fdiv)]
|
172 |
+
a = mpf(0.27)
|
173 |
+
b = mpf(1.13)
|
174 |
+
c = mpc(0.51+2.16j)
|
175 |
+
d = mpc(1.08-0.99j)
|
176 |
+
for x in [a,b,c,d]:
|
177 |
+
for y in [a,b,c,d]:
|
178 |
+
for op, fop in ops:
|
179 |
+
if fop is not fdiv:
|
180 |
+
mp.prec = 200
|
181 |
+
z0 = op(x,y)
|
182 |
+
mp.prec = 60
|
183 |
+
z1 = op(x,y)
|
184 |
+
mp.prec = 53
|
185 |
+
z2 = op(x,y)
|
186 |
+
assert fop(x, y, prec=60) == z1
|
187 |
+
assert fop(x, y) == z2
|
188 |
+
if fop is not fdiv:
|
189 |
+
assert fop(x, y, prec=inf) == z0
|
190 |
+
assert fop(x, y, dps=inf) == z0
|
191 |
+
assert fop(x, y, exact=True) == z0
|
192 |
+
assert fneg(fneg(z1, exact=True), prec=inf) == z1
|
193 |
+
assert fneg(z1) == -(+z1)
|
194 |
+
mp.dps = 15
|
195 |
+
|
196 |
+
def test_exact_integer_arithmetic():
|
197 |
+
# XXX: re-fix this so that all operations are tested with all rounding modes
|
198 |
+
random.seed(0)
|
199 |
+
for prec in [6, 10, 25, 40, 100, 250, 725]:
|
200 |
+
for rounding in ['d', 'u', 'f', 'c', 'n']:
|
201 |
+
mp.dps = prec
|
202 |
+
M = 10**(prec-2)
|
203 |
+
M2 = 10**(prec//2-2)
|
204 |
+
for i in range(10):
|
205 |
+
a = random.randint(-M, M)
|
206 |
+
b = random.randint(-M, M)
|
207 |
+
assert mpf(a, rounding=rounding) == a
|
208 |
+
assert int(mpf(a, rounding=rounding)) == a
|
209 |
+
assert int(mpf(str(a), rounding=rounding)) == a
|
210 |
+
assert mpf(a) + mpf(b) == a + b
|
211 |
+
assert mpf(a) - mpf(b) == a - b
|
212 |
+
assert -mpf(a) == -a
|
213 |
+
a = random.randint(-M2, M2)
|
214 |
+
b = random.randint(-M2, M2)
|
215 |
+
assert mpf(a) * mpf(b) == a*b
|
216 |
+
assert mpf_mul(from_int(a), from_int(b), mp.prec, rounding) == from_int(a*b)
|
217 |
+
mp.dps = 15
|
218 |
+
|
219 |
+
def test_odd_int_bug():
|
220 |
+
assert to_int(from_int(3), round_nearest) == 3
|
221 |
+
|
222 |
+
def test_str_1000_digits():
|
223 |
+
mp.dps = 1001
|
224 |
+
# last digit may be wrong
|
225 |
+
assert str(mpf(2)**0.5)[-10:-1] == '9518488472'[:9]
|
226 |
+
assert str(pi)[-10:-1] == '2164201989'[:9]
|
227 |
+
mp.dps = 15
|
228 |
+
|
229 |
+
def test_str_10000_digits():
|
230 |
+
mp.dps = 10001
|
231 |
+
# last digit may be wrong
|
232 |
+
assert str(mpf(2)**0.5)[-10:-1] == '5873258351'[:9]
|
233 |
+
assert str(pi)[-10:-1] == '5256375678'[:9]
|
234 |
+
mp.dps = 15
|
235 |
+
|
236 |
+
def test_monitor():
|
237 |
+
f = lambda x: x**2
|
238 |
+
a = []
|
239 |
+
b = []
|
240 |
+
g = monitor(f, a.append, b.append)
|
241 |
+
assert g(3) == 9
|
242 |
+
assert g(4) == 16
|
243 |
+
assert a[0] == ((3,), {})
|
244 |
+
assert b[0] == 9
|
245 |
+
|
246 |
+
def test_nint_distance():
|
247 |
+
assert nint_distance(mpf(-3)) == (-3, -inf)
|
248 |
+
assert nint_distance(mpc(-3)) == (-3, -inf)
|
249 |
+
assert nint_distance(mpf(-3.1)) == (-3, -3)
|
250 |
+
assert nint_distance(mpf(-3.01)) == (-3, -6)
|
251 |
+
assert nint_distance(mpf(-3.001)) == (-3, -9)
|
252 |
+
assert nint_distance(mpf(-3.0001)) == (-3, -13)
|
253 |
+
assert nint_distance(mpf(-2.9)) == (-3, -3)
|
254 |
+
assert nint_distance(mpf(-2.99)) == (-3, -6)
|
255 |
+
assert nint_distance(mpf(-2.999)) == (-3, -9)
|
256 |
+
assert nint_distance(mpf(-2.9999)) == (-3, -13)
|
257 |
+
assert nint_distance(mpc(-3+0.1j)) == (-3, -3)
|
258 |
+
assert nint_distance(mpc(-3+0.01j)) == (-3, -6)
|
259 |
+
assert nint_distance(mpc(-3.1+0.1j)) == (-3, -3)
|
260 |
+
assert nint_distance(mpc(-3.01+0.01j)) == (-3, -6)
|
261 |
+
assert nint_distance(mpc(-3.001+0.001j)) == (-3, -9)
|
262 |
+
assert nint_distance(mpf(0)) == (0, -inf)
|
263 |
+
assert nint_distance(mpf(0.01)) == (0, -6)
|
264 |
+
assert nint_distance(mpf('1e-100')) == (0, -332)
|
265 |
+
|
266 |
+
def test_floor_ceil_nint_frac():
|
267 |
+
mp.dps = 15
|
268 |
+
for n in range(-10,10):
|
269 |
+
assert floor(n) == n
|
270 |
+
assert floor(n+0.5) == n
|
271 |
+
assert ceil(n) == n
|
272 |
+
assert ceil(n+0.5) == n+1
|
273 |
+
assert nint(n) == n
|
274 |
+
# nint rounds to even
|
275 |
+
if n % 2 == 1:
|
276 |
+
assert nint(n+0.5) == n+1
|
277 |
+
else:
|
278 |
+
assert nint(n+0.5) == n
|
279 |
+
assert floor(inf) == inf
|
280 |
+
assert floor(ninf) == ninf
|
281 |
+
assert isnan(floor(nan))
|
282 |
+
assert ceil(inf) == inf
|
283 |
+
assert ceil(ninf) == ninf
|
284 |
+
assert isnan(ceil(nan))
|
285 |
+
assert nint(inf) == inf
|
286 |
+
assert nint(ninf) == ninf
|
287 |
+
assert isnan(nint(nan))
|
288 |
+
assert floor(0.1) == 0
|
289 |
+
assert floor(0.9) == 0
|
290 |
+
assert floor(-0.1) == -1
|
291 |
+
assert floor(-0.9) == -1
|
292 |
+
assert floor(10000000000.1) == 10000000000
|
293 |
+
assert floor(10000000000.9) == 10000000000
|
294 |
+
assert floor(-10000000000.1) == -10000000000-1
|
295 |
+
assert floor(-10000000000.9) == -10000000000-1
|
296 |
+
assert floor(1e-100) == 0
|
297 |
+
assert floor(-1e-100) == -1
|
298 |
+
assert floor(1e100) == 1e100
|
299 |
+
assert floor(-1e100) == -1e100
|
300 |
+
assert ceil(0.1) == 1
|
301 |
+
assert ceil(0.9) == 1
|
302 |
+
assert ceil(-0.1) == 0
|
303 |
+
assert ceil(-0.9) == 0
|
304 |
+
assert ceil(10000000000.1) == 10000000000+1
|
305 |
+
assert ceil(10000000000.9) == 10000000000+1
|
306 |
+
assert ceil(-10000000000.1) == -10000000000
|
307 |
+
assert ceil(-10000000000.9) == -10000000000
|
308 |
+
assert ceil(1e-100) == 1
|
309 |
+
assert ceil(-1e-100) == 0
|
310 |
+
assert ceil(1e100) == 1e100
|
311 |
+
assert ceil(-1e100) == -1e100
|
312 |
+
assert nint(0.1) == 0
|
313 |
+
assert nint(0.9) == 1
|
314 |
+
assert nint(-0.1) == 0
|
315 |
+
assert nint(-0.9) == -1
|
316 |
+
assert nint(10000000000.1) == 10000000000
|
317 |
+
assert nint(10000000000.9) == 10000000000+1
|
318 |
+
assert nint(-10000000000.1) == -10000000000
|
319 |
+
assert nint(-10000000000.9) == -10000000000-1
|
320 |
+
assert nint(1e-100) == 0
|
321 |
+
assert nint(-1e-100) == 0
|
322 |
+
assert nint(1e100) == 1e100
|
323 |
+
assert nint(-1e100) == -1e100
|
324 |
+
assert floor(3.2+4.6j) == 3+4j
|
325 |
+
assert ceil(3.2+4.6j) == 4+5j
|
326 |
+
assert nint(3.2+4.6j) == 3+5j
|
327 |
+
for n in range(-10,10):
|
328 |
+
assert frac(n) == 0
|
329 |
+
assert frac(0.25) == 0.25
|
330 |
+
assert frac(1.25) == 0.25
|
331 |
+
assert frac(2.25) == 0.25
|
332 |
+
assert frac(-0.25) == 0.75
|
333 |
+
assert frac(-1.25) == 0.75
|
334 |
+
assert frac(-2.25) == 0.75
|
335 |
+
assert frac('1e100000000000000') == 0
|
336 |
+
u = mpf('1e-100000000000000')
|
337 |
+
assert frac(u) == u
|
338 |
+
assert frac(-u) == 1 # rounding!
|
339 |
+
u = mpf('1e-400')
|
340 |
+
assert frac(-u, prec=0) == fsub(1, u, exact=True)
|
341 |
+
assert frac(3.25+4.75j) == 0.25+0.75j
|
342 |
+
|
343 |
+
def test_isnan_etc():
|
344 |
+
from mpmath.rational import mpq
|
345 |
+
assert isnan(nan) == True
|
346 |
+
assert isnan(3) == False
|
347 |
+
assert isnan(mpf(3)) == False
|
348 |
+
assert isnan(inf) == False
|
349 |
+
assert isnan(mpc(2,nan)) == True
|
350 |
+
assert isnan(mpc(2,nan)) == True
|
351 |
+
assert isnan(mpc(nan,nan)) == True
|
352 |
+
assert isnan(mpc(2,2)) == False
|
353 |
+
assert isnan(mpc(nan,inf)) == True
|
354 |
+
assert isnan(mpc(inf,inf)) == False
|
355 |
+
assert isnan(mpq((3,2))) == False
|
356 |
+
assert isnan(mpq((0,1))) == False
|
357 |
+
assert isinf(inf) == True
|
358 |
+
assert isinf(-inf) == True
|
359 |
+
assert isinf(3) == False
|
360 |
+
assert isinf(nan) == False
|
361 |
+
assert isinf(3+4j) == False
|
362 |
+
assert isinf(mpc(inf)) == True
|
363 |
+
assert isinf(mpc(3,inf)) == True
|
364 |
+
assert isinf(mpc(inf,3)) == True
|
365 |
+
assert isinf(mpc(inf,inf)) == True
|
366 |
+
assert isinf(mpc(nan,inf)) == True
|
367 |
+
assert isinf(mpc(inf,nan)) == True
|
368 |
+
assert isinf(mpc(nan,nan)) == False
|
369 |
+
assert isinf(mpq((3,2))) == False
|
370 |
+
assert isinf(mpq((0,1))) == False
|
371 |
+
assert isnormal(3) == True
|
372 |
+
assert isnormal(3.5) == True
|
373 |
+
assert isnormal(mpf(3.5)) == True
|
374 |
+
assert isnormal(0) == False
|
375 |
+
assert isnormal(mpf(0)) == False
|
376 |
+
assert isnormal(0.0) == False
|
377 |
+
assert isnormal(inf) == False
|
378 |
+
assert isnormal(-inf) == False
|
379 |
+
assert isnormal(nan) == False
|
380 |
+
assert isnormal(float(inf)) == False
|
381 |
+
assert isnormal(mpc(0,0)) == False
|
382 |
+
assert isnormal(mpc(3,0)) == True
|
383 |
+
assert isnormal(mpc(0,3)) == True
|
384 |
+
assert isnormal(mpc(3,3)) == True
|
385 |
+
assert isnormal(mpc(0,nan)) == False
|
386 |
+
assert isnormal(mpc(0,inf)) == False
|
387 |
+
assert isnormal(mpc(3,nan)) == False
|
388 |
+
assert isnormal(mpc(3,inf)) == False
|
389 |
+
assert isnormal(mpc(3,-inf)) == False
|
390 |
+
assert isnormal(mpc(nan,0)) == False
|
391 |
+
assert isnormal(mpc(inf,0)) == False
|
392 |
+
assert isnormal(mpc(nan,3)) == False
|
393 |
+
assert isnormal(mpc(inf,3)) == False
|
394 |
+
assert isnormal(mpc(inf,nan)) == False
|
395 |
+
assert isnormal(mpc(nan,inf)) == False
|
396 |
+
assert isnormal(mpc(nan,nan)) == False
|
397 |
+
assert isnormal(mpc(inf,inf)) == False
|
398 |
+
assert isnormal(mpq((3,2))) == True
|
399 |
+
assert isnormal(mpq((0,1))) == False
|
400 |
+
assert isint(3) == True
|
401 |
+
assert isint(0) == True
|
402 |
+
assert isint(long(3)) == True
|
403 |
+
assert isint(long(0)) == True
|
404 |
+
assert isint(mpf(3)) == True
|
405 |
+
assert isint(mpf(0)) == True
|
406 |
+
assert isint(mpf(-3)) == True
|
407 |
+
assert isint(mpf(3.2)) == False
|
408 |
+
assert isint(3.2) == False
|
409 |
+
assert isint(nan) == False
|
410 |
+
assert isint(inf) == False
|
411 |
+
assert isint(-inf) == False
|
412 |
+
assert isint(mpc(0)) == True
|
413 |
+
assert isint(mpc(3)) == True
|
414 |
+
assert isint(mpc(3.2)) == False
|
415 |
+
assert isint(mpc(3,inf)) == False
|
416 |
+
assert isint(mpc(inf)) == False
|
417 |
+
assert isint(mpc(3,2)) == False
|
418 |
+
assert isint(mpc(0,2)) == False
|
419 |
+
assert isint(mpc(3,2),gaussian=True) == True
|
420 |
+
assert isint(mpc(3,0),gaussian=True) == True
|
421 |
+
assert isint(mpc(0,3),gaussian=True) == True
|
422 |
+
assert isint(3+4j) == False
|
423 |
+
assert isint(3+4j, gaussian=True) == True
|
424 |
+
assert isint(3+0j) == True
|
425 |
+
assert isint(mpq((3,2))) == False
|
426 |
+
assert isint(mpq((3,9))) == False
|
427 |
+
assert isint(mpq((9,3))) == True
|
428 |
+
assert isint(mpq((0,4))) == True
|
429 |
+
assert isint(mpq((1,1))) == True
|
430 |
+
assert isint(mpq((-1,1))) == True
|
431 |
+
assert mp.isnpint(0) == True
|
432 |
+
assert mp.isnpint(1) == False
|
433 |
+
assert mp.isnpint(-1) == True
|
434 |
+
assert mp.isnpint(-1.1) == False
|
435 |
+
assert mp.isnpint(-1.0) == True
|
436 |
+
assert mp.isnpint(mp.mpq(1,2)) == False
|
437 |
+
assert mp.isnpint(mp.mpq(-1,2)) == False
|
438 |
+
assert mp.isnpint(mp.mpq(-3,1)) == True
|
439 |
+
assert mp.isnpint(mp.mpq(0,1)) == True
|
440 |
+
assert mp.isnpint(mp.mpq(1,1)) == False
|
441 |
+
assert mp.isnpint(0+0j) == True
|
442 |
+
assert mp.isnpint(-1+0j) == True
|
443 |
+
assert mp.isnpint(-1.1+0j) == False
|
444 |
+
assert mp.isnpint(-1+0.1j) == False
|
445 |
+
assert mp.isnpint(0+0.1j) == False
|
446 |
+
|
447 |
+
|
448 |
+
def test_issue_438():
|
449 |
+
assert mpf(finf) == mpf('inf')
|
450 |
+
assert mpf(fninf) == mpf('-inf')
|
451 |
+
assert mpf(fnan)._mpf_ == mpf('nan')._mpf_
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_bitwise.py
ADDED
@@ -0,0 +1,188 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
"""
|
2 |
+
Test bit-level integer and mpf operations
|
3 |
+
"""
|
4 |
+
|
5 |
+
from mpmath import *
|
6 |
+
from mpmath.libmp import *
|
7 |
+
|
8 |
+
def test_bitcount():
|
9 |
+
assert bitcount(0) == 0
|
10 |
+
assert bitcount(1) == 1
|
11 |
+
assert bitcount(7) == 3
|
12 |
+
assert bitcount(8) == 4
|
13 |
+
assert bitcount(2**100) == 101
|
14 |
+
assert bitcount(2**100-1) == 100
|
15 |
+
|
16 |
+
def test_trailing():
|
17 |
+
assert trailing(0) == 0
|
18 |
+
assert trailing(1) == 0
|
19 |
+
assert trailing(2) == 1
|
20 |
+
assert trailing(7) == 0
|
21 |
+
assert trailing(8) == 3
|
22 |
+
assert trailing(2**100) == 100
|
23 |
+
assert trailing(2**100-1) == 0
|
24 |
+
|
25 |
+
def test_round_down():
|
26 |
+
assert from_man_exp(0, -4, 4, round_down)[:3] == (0, 0, 0)
|
27 |
+
assert from_man_exp(0xf0, -4, 4, round_down)[:3] == (0, 15, 0)
|
28 |
+
assert from_man_exp(0xf1, -4, 4, round_down)[:3] == (0, 15, 0)
|
29 |
+
assert from_man_exp(0xff, -4, 4, round_down)[:3] == (0, 15, 0)
|
30 |
+
assert from_man_exp(-0xf0, -4, 4, round_down)[:3] == (1, 15, 0)
|
31 |
+
assert from_man_exp(-0xf1, -4, 4, round_down)[:3] == (1, 15, 0)
|
32 |
+
assert from_man_exp(-0xff, -4, 4, round_down)[:3] == (1, 15, 0)
|
33 |
+
|
34 |
+
def test_round_up():
|
35 |
+
assert from_man_exp(0, -4, 4, round_up)[:3] == (0, 0, 0)
|
36 |
+
assert from_man_exp(0xf0, -4, 4, round_up)[:3] == (0, 15, 0)
|
37 |
+
assert from_man_exp(0xf1, -4, 4, round_up)[:3] == (0, 1, 4)
|
38 |
+
assert from_man_exp(0xff, -4, 4, round_up)[:3] == (0, 1, 4)
|
39 |
+
assert from_man_exp(-0xf0, -4, 4, round_up)[:3] == (1, 15, 0)
|
40 |
+
assert from_man_exp(-0xf1, -4, 4, round_up)[:3] == (1, 1, 4)
|
41 |
+
assert from_man_exp(-0xff, -4, 4, round_up)[:3] == (1, 1, 4)
|
42 |
+
|
43 |
+
def test_round_floor():
|
44 |
+
assert from_man_exp(0, -4, 4, round_floor)[:3] == (0, 0, 0)
|
45 |
+
assert from_man_exp(0xf0, -4, 4, round_floor)[:3] == (0, 15, 0)
|
46 |
+
assert from_man_exp(0xf1, -4, 4, round_floor)[:3] == (0, 15, 0)
|
47 |
+
assert from_man_exp(0xff, -4, 4, round_floor)[:3] == (0, 15, 0)
|
48 |
+
assert from_man_exp(-0xf0, -4, 4, round_floor)[:3] == (1, 15, 0)
|
49 |
+
assert from_man_exp(-0xf1, -4, 4, round_floor)[:3] == (1, 1, 4)
|
50 |
+
assert from_man_exp(-0xff, -4, 4, round_floor)[:3] == (1, 1, 4)
|
51 |
+
|
52 |
+
def test_round_ceiling():
|
53 |
+
assert from_man_exp(0, -4, 4, round_ceiling)[:3] == (0, 0, 0)
|
54 |
+
assert from_man_exp(0xf0, -4, 4, round_ceiling)[:3] == (0, 15, 0)
|
55 |
+
assert from_man_exp(0xf1, -4, 4, round_ceiling)[:3] == (0, 1, 4)
|
56 |
+
assert from_man_exp(0xff, -4, 4, round_ceiling)[:3] == (0, 1, 4)
|
57 |
+
assert from_man_exp(-0xf0, -4, 4, round_ceiling)[:3] == (1, 15, 0)
|
58 |
+
assert from_man_exp(-0xf1, -4, 4, round_ceiling)[:3] == (1, 15, 0)
|
59 |
+
assert from_man_exp(-0xff, -4, 4, round_ceiling)[:3] == (1, 15, 0)
|
60 |
+
|
61 |
+
def test_round_nearest():
|
62 |
+
assert from_man_exp(0, -4, 4, round_nearest)[:3] == (0, 0, 0)
|
63 |
+
assert from_man_exp(0xf0, -4, 4, round_nearest)[:3] == (0, 15, 0)
|
64 |
+
assert from_man_exp(0xf7, -4, 4, round_nearest)[:3] == (0, 15, 0)
|
65 |
+
assert from_man_exp(0xf8, -4, 4, round_nearest)[:3] == (0, 1, 4) # 1111.1000 -> 10000.0
|
66 |
+
assert from_man_exp(0xf9, -4, 4, round_nearest)[:3] == (0, 1, 4) # 1111.1001 -> 10000.0
|
67 |
+
assert from_man_exp(0xe8, -4, 4, round_nearest)[:3] == (0, 7, 1) # 1110.1000 -> 1110.0
|
68 |
+
assert from_man_exp(0xe9, -4, 4, round_nearest)[:3] == (0, 15, 0) # 1110.1001 -> 1111.0
|
69 |
+
assert from_man_exp(-0xf0, -4, 4, round_nearest)[:3] == (1, 15, 0)
|
70 |
+
assert from_man_exp(-0xf7, -4, 4, round_nearest)[:3] == (1, 15, 0)
|
71 |
+
assert from_man_exp(-0xf8, -4, 4, round_nearest)[:3] == (1, 1, 4)
|
72 |
+
assert from_man_exp(-0xf9, -4, 4, round_nearest)[:3] == (1, 1, 4)
|
73 |
+
assert from_man_exp(-0xe8, -4, 4, round_nearest)[:3] == (1, 7, 1)
|
74 |
+
assert from_man_exp(-0xe9, -4, 4, round_nearest)[:3] == (1, 15, 0)
|
75 |
+
|
76 |
+
def test_rounding_bugs():
|
77 |
+
# 1 less than power-of-two cases
|
78 |
+
assert from_man_exp(72057594037927935, -56, 53, round_up) == (0, 1, 0, 1)
|
79 |
+
assert from_man_exp(73786976294838205979, -65, 53, round_nearest) == (0, 1, 1, 1)
|
80 |
+
assert from_man_exp(31, 0, 4, round_up) == (0, 1, 5, 1)
|
81 |
+
assert from_man_exp(-31, 0, 4, round_floor) == (1, 1, 5, 1)
|
82 |
+
assert from_man_exp(255, 0, 7, round_up) == (0, 1, 8, 1)
|
83 |
+
assert from_man_exp(-255, 0, 7, round_floor) == (1, 1, 8, 1)
|
84 |
+
|
85 |
+
def test_rounding_issue_200():
|
86 |
+
a = from_man_exp(9867,-100)
|
87 |
+
b = from_man_exp(9867,-200)
|
88 |
+
c = from_man_exp(-1,0)
|
89 |
+
z = (1, 1023, -10, 10)
|
90 |
+
assert mpf_add(a, c, 10, 'd') == z
|
91 |
+
assert mpf_add(b, c, 10, 'd') == z
|
92 |
+
assert mpf_add(c, a, 10, 'd') == z
|
93 |
+
assert mpf_add(c, b, 10, 'd') == z
|
94 |
+
|
95 |
+
def test_perturb():
|
96 |
+
a = fone
|
97 |
+
b = from_float(0.99999999999999989)
|
98 |
+
c = from_float(1.0000000000000002)
|
99 |
+
assert mpf_perturb(a, 0, 53, round_nearest) == a
|
100 |
+
assert mpf_perturb(a, 1, 53, round_nearest) == a
|
101 |
+
assert mpf_perturb(a, 0, 53, round_up) == c
|
102 |
+
assert mpf_perturb(a, 0, 53, round_ceiling) == c
|
103 |
+
assert mpf_perturb(a, 0, 53, round_down) == a
|
104 |
+
assert mpf_perturb(a, 0, 53, round_floor) == a
|
105 |
+
assert mpf_perturb(a, 1, 53, round_up) == a
|
106 |
+
assert mpf_perturb(a, 1, 53, round_ceiling) == a
|
107 |
+
assert mpf_perturb(a, 1, 53, round_down) == b
|
108 |
+
assert mpf_perturb(a, 1, 53, round_floor) == b
|
109 |
+
a = mpf_neg(a)
|
110 |
+
b = mpf_neg(b)
|
111 |
+
c = mpf_neg(c)
|
112 |
+
assert mpf_perturb(a, 0, 53, round_nearest) == a
|
113 |
+
assert mpf_perturb(a, 1, 53, round_nearest) == a
|
114 |
+
assert mpf_perturb(a, 0, 53, round_up) == a
|
115 |
+
assert mpf_perturb(a, 0, 53, round_floor) == a
|
116 |
+
assert mpf_perturb(a, 0, 53, round_down) == b
|
117 |
+
assert mpf_perturb(a, 0, 53, round_ceiling) == b
|
118 |
+
assert mpf_perturb(a, 1, 53, round_up) == c
|
119 |
+
assert mpf_perturb(a, 1, 53, round_floor) == c
|
120 |
+
assert mpf_perturb(a, 1, 53, round_down) == a
|
121 |
+
assert mpf_perturb(a, 1, 53, round_ceiling) == a
|
122 |
+
|
123 |
+
def test_add_exact():
|
124 |
+
ff = from_float
|
125 |
+
assert mpf_add(ff(3.0), ff(2.5)) == ff(5.5)
|
126 |
+
assert mpf_add(ff(3.0), ff(-2.5)) == ff(0.5)
|
127 |
+
assert mpf_add(ff(-3.0), ff(2.5)) == ff(-0.5)
|
128 |
+
assert mpf_add(ff(-3.0), ff(-2.5)) == ff(-5.5)
|
129 |
+
assert mpf_sub(mpf_add(fone, ff(1e-100)), fone) == ff(1e-100)
|
130 |
+
assert mpf_sub(mpf_add(ff(1e-100), fone), fone) == ff(1e-100)
|
131 |
+
assert mpf_sub(mpf_add(fone, ff(-1e-100)), fone) == ff(-1e-100)
|
132 |
+
assert mpf_sub(mpf_add(ff(-1e-100), fone), fone) == ff(-1e-100)
|
133 |
+
assert mpf_add(fone, fzero) == fone
|
134 |
+
assert mpf_add(fzero, fone) == fone
|
135 |
+
assert mpf_add(fzero, fzero) == fzero
|
136 |
+
|
137 |
+
def test_long_exponent_shifts():
|
138 |
+
mp.dps = 15
|
139 |
+
# Check for possible bugs due to exponent arithmetic overflow
|
140 |
+
# in a C implementation
|
141 |
+
x = mpf(1)
|
142 |
+
for p in [32, 64]:
|
143 |
+
a = ldexp(1,2**(p-1))
|
144 |
+
b = ldexp(1,2**p)
|
145 |
+
c = ldexp(1,2**(p+1))
|
146 |
+
d = ldexp(1,-2**(p-1))
|
147 |
+
e = ldexp(1,-2**p)
|
148 |
+
f = ldexp(1,-2**(p+1))
|
149 |
+
assert (x+a) == a
|
150 |
+
assert (x+b) == b
|
151 |
+
assert (x+c) == c
|
152 |
+
assert (x+d) == x
|
153 |
+
assert (x+e) == x
|
154 |
+
assert (x+f) == x
|
155 |
+
assert (a+x) == a
|
156 |
+
assert (b+x) == b
|
157 |
+
assert (c+x) == c
|
158 |
+
assert (d+x) == x
|
159 |
+
assert (e+x) == x
|
160 |
+
assert (f+x) == x
|
161 |
+
assert (x-a) == -a
|
162 |
+
assert (x-b) == -b
|
163 |
+
assert (x-c) == -c
|
164 |
+
assert (x-d) == x
|
165 |
+
assert (x-e) == x
|
166 |
+
assert (x-f) == x
|
167 |
+
assert (a-x) == a
|
168 |
+
assert (b-x) == b
|
169 |
+
assert (c-x) == c
|
170 |
+
assert (d-x) == -x
|
171 |
+
assert (e-x) == -x
|
172 |
+
assert (f-x) == -x
|
173 |
+
|
174 |
+
def test_float_rounding():
|
175 |
+
mp.prec = 64
|
176 |
+
for x in [mpf(1), mpf(1)+eps, mpf(1)-eps, -mpf(1)+eps, -mpf(1)-eps]:
|
177 |
+
fa = float(x)
|
178 |
+
fb = float(fadd(x,0,prec=53,rounding='n'))
|
179 |
+
assert fa == fb
|
180 |
+
z = mpc(x,x)
|
181 |
+
ca = complex(z)
|
182 |
+
cb = complex(fadd(z,0,prec=53,rounding='n'))
|
183 |
+
assert ca == cb
|
184 |
+
for rnd in ['n', 'd', 'u', 'f', 'c']:
|
185 |
+
fa = to_float(x._mpf_, rnd=rnd)
|
186 |
+
fb = to_float(fadd(x,0,prec=53,rounding=rnd)._mpf_, rnd=rnd)
|
187 |
+
assert fa == fb
|
188 |
+
mp.prec = 53
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_calculus.py
ADDED
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pytest
|
2 |
+
from mpmath import *
|
3 |
+
|
4 |
+
def test_approximation():
|
5 |
+
mp.dps = 15
|
6 |
+
f = lambda x: cos(2-2*x)/x
|
7 |
+
p, err = chebyfit(f, [2, 4], 8, error=True)
|
8 |
+
assert err < 1e-5
|
9 |
+
for i in range(10):
|
10 |
+
x = 2 + i/5.
|
11 |
+
assert abs(polyval(p, x) - f(x)) < err
|
12 |
+
|
13 |
+
def test_limits():
|
14 |
+
mp.dps = 15
|
15 |
+
assert limit(lambda x: (x-sin(x))/x**3, 0).ae(mpf(1)/6)
|
16 |
+
assert limit(lambda n: (1+1/n)**n, inf).ae(e)
|
17 |
+
|
18 |
+
def test_polyval():
|
19 |
+
assert polyval([], 3) == 0
|
20 |
+
assert polyval([0], 3) == 0
|
21 |
+
assert polyval([5], 3) == 5
|
22 |
+
# 4x^3 - 2x + 5
|
23 |
+
p = [4, 0, -2, 5]
|
24 |
+
assert polyval(p,4) == 253
|
25 |
+
assert polyval(p,4,derivative=True) == (253, 190)
|
26 |
+
|
27 |
+
def test_polyroots():
|
28 |
+
p = polyroots([1,-4])
|
29 |
+
assert p[0].ae(4)
|
30 |
+
p, q = polyroots([1,2,3])
|
31 |
+
assert p.ae(-1 - sqrt(2)*j)
|
32 |
+
assert q.ae(-1 + sqrt(2)*j)
|
33 |
+
#this is not a real test, it only tests a specific case
|
34 |
+
assert polyroots([1]) == []
|
35 |
+
pytest.raises(ValueError, lambda: polyroots([0]))
|
36 |
+
|
37 |
+
def test_polyroots_legendre():
|
38 |
+
n = 64
|
39 |
+
coeffs = [11975573020964041433067793888190275875, 0,
|
40 |
+
-190100434726484311252477736051902332000, 0,
|
41 |
+
1437919688271127330313741595496589239248, 0,
|
42 |
+
-6897338342113537600691931230430793911840, 0,
|
43 |
+
23556405536185284408974715545252277554280, 0,
|
44 |
+
-60969520211303089058522793175947071316960, 0,
|
45 |
+
124284021969194758465450309166353645376880, 0,
|
46 |
+
-204721258548015217049921875719981284186016, 0,
|
47 |
+
277415422258095841688223780704620656114900, 0,
|
48 |
+
-313237834141273382807123548182995095192800, 0,
|
49 |
+
297432255354328395601259515935229287637200, 0,
|
50 |
+
-239057700565161140389797367947941296605600, 0,
|
51 |
+
163356095386193445933028201431093219347160, 0,
|
52 |
+
-95158890516229191805647495979277603503200, 0,
|
53 |
+
47310254620162038075933656063247634556400, 0,
|
54 |
+
-20071017111583894941305187420771723751200, 0,
|
55 |
+
7255051932731034189479516844750603752850, 0,
|
56 |
+
-2228176940331017311443863996901733412640, 0,
|
57 |
+
579006552594977616773047095969088431600, 0,
|
58 |
+
-126584428502545713788439446082310831200, 0,
|
59 |
+
23112325428835593809686977515028663000, 0,
|
60 |
+
-3491517141958743235617737161547844000, 0,
|
61 |
+
431305058712550634988073414073557200, 0,
|
62 |
+
-42927166660756742088912492757452000, 0,
|
63 |
+
3378527005707706553294038781836500, 0,
|
64 |
+
-205277590220215081719131470288800, 0,
|
65 |
+
9330799555464321896324157740400, 0,
|
66 |
+
-304114948474392713657972548576, 0,
|
67 |
+
6695289961520387531608984680, 0,
|
68 |
+
-91048139350447232095702560, 0,
|
69 |
+
659769125727878493447120, 0,
|
70 |
+
-1905929106580294155360, 0,
|
71 |
+
916312070471295267]
|
72 |
+
|
73 |
+
with mp.workdps(3):
|
74 |
+
with pytest.raises(mp.NoConvergence):
|
75 |
+
polyroots(coeffs, maxsteps=5, cleanup=True, error=False,
|
76 |
+
extraprec=n*10)
|
77 |
+
|
78 |
+
roots = polyroots(coeffs, maxsteps=50, cleanup=True, error=False,
|
79 |
+
extraprec=n*10)
|
80 |
+
roots = [str(r) for r in roots]
|
81 |
+
assert roots == \
|
82 |
+
['-0.999', '-0.996', '-0.991', '-0.983', '-0.973', '-0.961',
|
83 |
+
'-0.946', '-0.93', '-0.911', '-0.889', '-0.866', '-0.841',
|
84 |
+
'-0.813', '-0.784', '-0.753', '-0.72', '-0.685', '-0.649',
|
85 |
+
'-0.611', '-0.572', '-0.531', '-0.489', '-0.446', '-0.402',
|
86 |
+
'-0.357', '-0.311', '-0.265', '-0.217', '-0.17', '-0.121',
|
87 |
+
'-0.073', '-0.0243', '0.0243', '0.073', '0.121', '0.17', '0.217',
|
88 |
+
'0.265', '0.311', '0.357', '0.402', '0.446', '0.489', '0.531',
|
89 |
+
'0.572', '0.611', '0.649', '0.685', '0.72', '0.753', '0.784',
|
90 |
+
'0.813', '0.841', '0.866', '0.889', '0.911', '0.93', '0.946',
|
91 |
+
'0.961', '0.973', '0.983', '0.991', '0.996', '0.999']
|
92 |
+
|
93 |
+
def test_polyroots_legendre_init():
|
94 |
+
extra_prec = 100
|
95 |
+
coeffs = [11975573020964041433067793888190275875, 0,
|
96 |
+
-190100434726484311252477736051902332000, 0,
|
97 |
+
1437919688271127330313741595496589239248, 0,
|
98 |
+
-6897338342113537600691931230430793911840, 0,
|
99 |
+
23556405536185284408974715545252277554280, 0,
|
100 |
+
-60969520211303089058522793175947071316960, 0,
|
101 |
+
124284021969194758465450309166353645376880, 0,
|
102 |
+
-204721258548015217049921875719981284186016, 0,
|
103 |
+
277415422258095841688223780704620656114900, 0,
|
104 |
+
-313237834141273382807123548182995095192800, 0,
|
105 |
+
297432255354328395601259515935229287637200, 0,
|
106 |
+
-239057700565161140389797367947941296605600, 0,
|
107 |
+
163356095386193445933028201431093219347160, 0,
|
108 |
+
-95158890516229191805647495979277603503200, 0,
|
109 |
+
47310254620162038075933656063247634556400, 0,
|
110 |
+
-20071017111583894941305187420771723751200, 0,
|
111 |
+
7255051932731034189479516844750603752850, 0,
|
112 |
+
-2228176940331017311443863996901733412640, 0,
|
113 |
+
579006552594977616773047095969088431600, 0,
|
114 |
+
-126584428502545713788439446082310831200, 0,
|
115 |
+
23112325428835593809686977515028663000, 0,
|
116 |
+
-3491517141958743235617737161547844000, 0,
|
117 |
+
431305058712550634988073414073557200, 0,
|
118 |
+
-42927166660756742088912492757452000, 0,
|
119 |
+
3378527005707706553294038781836500, 0,
|
120 |
+
-205277590220215081719131470288800, 0,
|
121 |
+
9330799555464321896324157740400, 0,
|
122 |
+
-304114948474392713657972548576, 0,
|
123 |
+
6695289961520387531608984680, 0,
|
124 |
+
-91048139350447232095702560, 0,
|
125 |
+
659769125727878493447120, 0,
|
126 |
+
-1905929106580294155360, 0,
|
127 |
+
916312070471295267]
|
128 |
+
|
129 |
+
roots_init = matrix(['-0.999', '-0.996', '-0.991', '-0.983', '-0.973',
|
130 |
+
'-0.961', '-0.946', '-0.93', '-0.911', '-0.889',
|
131 |
+
'-0.866', '-0.841', '-0.813', '-0.784', '-0.753',
|
132 |
+
'-0.72', '-0.685', '-0.649', '-0.611', '-0.572',
|
133 |
+
'-0.531', '-0.489', '-0.446', '-0.402', '-0.357',
|
134 |
+
'-0.311', '-0.265', '-0.217', '-0.17', '-0.121',
|
135 |
+
'-0.073', '-0.0243', '0.0243', '0.073', '0.121',
|
136 |
+
'0.17', '0.217', '0.265', ' 0.311', '0.357',
|
137 |
+
'0.402', '0.446', '0.489', '0.531', '0.572',
|
138 |
+
'0.611', '0.649', '0.685', '0.72', '0.753',
|
139 |
+
'0.784', '0.813', '0.841', '0.866', '0.889',
|
140 |
+
'0.911', '0.93', '0.946', '0.961', '0.973',
|
141 |
+
'0.983', '0.991', '0.996', '0.999', '1.0'])
|
142 |
+
with mp.workdps(2*mp.dps):
|
143 |
+
roots_exact = polyroots(coeffs, maxsteps=50, cleanup=True, error=False,
|
144 |
+
extraprec=2*extra_prec)
|
145 |
+
with pytest.raises(mp.NoConvergence):
|
146 |
+
polyroots(coeffs, maxsteps=5, cleanup=True, error=False,
|
147 |
+
extraprec=extra_prec)
|
148 |
+
roots,err = polyroots(coeffs, maxsteps=5, cleanup=True, error=True,
|
149 |
+
extraprec=extra_prec,roots_init=roots_init)
|
150 |
+
assert max(matrix(roots_exact)-matrix(roots).apply(abs)) < err
|
151 |
+
roots1,err1 = polyroots(coeffs, maxsteps=25, cleanup=True, error=True,
|
152 |
+
extraprec=extra_prec,roots_init=roots_init[:60])
|
153 |
+
assert max(matrix(roots_exact)-matrix(roots1).apply(abs)) < err1
|
154 |
+
|
155 |
+
def test_pade():
|
156 |
+
one = mpf(1)
|
157 |
+
mp.dps = 20
|
158 |
+
N = 10
|
159 |
+
a = [one]
|
160 |
+
k = 1
|
161 |
+
for i in range(1, N+1):
|
162 |
+
k *= i
|
163 |
+
a.append(one/k)
|
164 |
+
p, q = pade(a, N//2, N//2)
|
165 |
+
for x in arange(0, 1, 0.1):
|
166 |
+
r = polyval(p[::-1], x)/polyval(q[::-1], x)
|
167 |
+
assert(r.ae(exp(x), 1.0e-10))
|
168 |
+
mp.dps = 15
|
169 |
+
|
170 |
+
def test_fourier():
|
171 |
+
mp.dps = 15
|
172 |
+
c, s = fourier(lambda x: x+1, [-1, 2], 2)
|
173 |
+
#plot([lambda x: x+1, lambda x: fourierval((c, s), [-1, 2], x)], [-1, 2])
|
174 |
+
assert c[0].ae(1.5)
|
175 |
+
assert c[1].ae(-3*sqrt(3)/(2*pi))
|
176 |
+
assert c[2].ae(3*sqrt(3)/(4*pi))
|
177 |
+
assert s[0] == 0
|
178 |
+
assert s[1].ae(3/(2*pi))
|
179 |
+
assert s[2].ae(3/(4*pi))
|
180 |
+
assert fourierval((c, s), [-1, 2], 1).ae(1.9134966715663442)
|
181 |
+
|
182 |
+
def test_differint():
|
183 |
+
mp.dps = 15
|
184 |
+
assert differint(lambda t: t, 2, -0.5).ae(8*sqrt(2/pi)/3)
|
185 |
+
|
186 |
+
def test_invlap():
|
187 |
+
mp.dps = 15
|
188 |
+
t = 0.01
|
189 |
+
fp = lambda p: 1/(p+1)**2
|
190 |
+
ft = lambda t: t*exp(-t)
|
191 |
+
ftt = ft(t)
|
192 |
+
assert invertlaplace(fp,t,method='talbot').ae(ftt)
|
193 |
+
assert invertlaplace(fp,t,method='stehfest').ae(ftt)
|
194 |
+
assert invertlaplace(fp,t,method='dehoog').ae(ftt)
|
195 |
+
assert invertlaplace(fp,t,method='cohen').ae(ftt)
|
196 |
+
t = 1.0
|
197 |
+
ftt = ft(t)
|
198 |
+
assert invertlaplace(fp,t,method='talbot').ae(ftt)
|
199 |
+
assert invertlaplace(fp,t,method='stehfest').ae(ftt)
|
200 |
+
assert invertlaplace(fp,t,method='dehoog').ae(ftt)
|
201 |
+
assert invertlaplace(fp,t,method='cohen').ae(ftt)
|
202 |
+
|
203 |
+
t = 0.01
|
204 |
+
fp = lambda p: log(p)/p
|
205 |
+
ft = lambda t: -euler-log(t)
|
206 |
+
ftt = ft(t)
|
207 |
+
assert invertlaplace(fp,t,method='talbot').ae(ftt)
|
208 |
+
assert invertlaplace(fp,t,method='stehfest').ae(ftt)
|
209 |
+
assert invertlaplace(fp,t,method='dehoog').ae(ftt)
|
210 |
+
assert invertlaplace(fp,t,method='cohen').ae(ftt)
|
211 |
+
t = 1.0
|
212 |
+
ftt = ft(t)
|
213 |
+
assert invertlaplace(fp,t,method='talbot').ae(ftt)
|
214 |
+
assert invertlaplace(fp,t,method='stehfest').ae(ftt)
|
215 |
+
assert invertlaplace(fp,t,method='dehoog').ae(ftt)
|
216 |
+
assert invertlaplace(fp,t,method='cohen').ae(ftt)
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_compatibility.py
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from mpmath import *
|
2 |
+
from random import seed, randint, random
|
3 |
+
import math
|
4 |
+
|
5 |
+
# Test compatibility with Python floats, which are
|
6 |
+
# IEEE doubles (53-bit)
|
7 |
+
|
8 |
+
N = 5000
|
9 |
+
seed(1)
|
10 |
+
|
11 |
+
# Choosing exponents between roughly -140, 140 ensures that
|
12 |
+
# the Python floats don't overflow or underflow
|
13 |
+
xs = [(random()-1) * 10**randint(-140, 140) for x in range(N)]
|
14 |
+
ys = [(random()-1) * 10**randint(-140, 140) for x in range(N)]
|
15 |
+
|
16 |
+
# include some equal values
|
17 |
+
ys[int(N*0.8):] = xs[int(N*0.8):]
|
18 |
+
|
19 |
+
# Detect whether Python is compiled to use 80-bit floating-point
|
20 |
+
# instructions, in which case the double compatibility test breaks
|
21 |
+
uses_x87 = -4.1974624032366689e+117 / -8.4657370748010221e-47 \
|
22 |
+
== 4.9581771393902231e+163
|
23 |
+
|
24 |
+
def test_double_compatibility():
|
25 |
+
mp.prec = 53
|
26 |
+
for x, y in zip(xs, ys):
|
27 |
+
mpx = mpf(x)
|
28 |
+
mpy = mpf(y)
|
29 |
+
assert mpf(x) == x
|
30 |
+
assert (mpx < mpy) == (x < y)
|
31 |
+
assert (mpx > mpy) == (x > y)
|
32 |
+
assert (mpx == mpy) == (x == y)
|
33 |
+
assert (mpx != mpy) == (x != y)
|
34 |
+
assert (mpx <= mpy) == (x <= y)
|
35 |
+
assert (mpx >= mpy) == (x >= y)
|
36 |
+
assert mpx == mpx
|
37 |
+
if uses_x87:
|
38 |
+
mp.prec = 64
|
39 |
+
a = mpx + mpy
|
40 |
+
b = mpx * mpy
|
41 |
+
c = mpx / mpy
|
42 |
+
d = mpx % mpy
|
43 |
+
mp.prec = 53
|
44 |
+
assert +a == x + y
|
45 |
+
assert +b == x * y
|
46 |
+
assert +c == x / y
|
47 |
+
assert +d == x % y
|
48 |
+
else:
|
49 |
+
assert mpx + mpy == x + y
|
50 |
+
assert mpx * mpy == x * y
|
51 |
+
assert mpx / mpy == x / y
|
52 |
+
assert mpx % mpy == x % y
|
53 |
+
assert abs(mpx) == abs(x)
|
54 |
+
assert mpf(repr(x)) == x
|
55 |
+
assert ceil(mpx) == math.ceil(x)
|
56 |
+
assert floor(mpx) == math.floor(x)
|
57 |
+
|
58 |
+
def test_sqrt():
|
59 |
+
# this fails quite often. it appers to be float
|
60 |
+
# that rounds the wrong way, not mpf
|
61 |
+
fail = 0
|
62 |
+
mp.prec = 53
|
63 |
+
for x in xs:
|
64 |
+
x = abs(x)
|
65 |
+
mp.prec = 100
|
66 |
+
mp_high = mpf(x)**0.5
|
67 |
+
mp.prec = 53
|
68 |
+
mp_low = mpf(x)**0.5
|
69 |
+
fp = x**0.5
|
70 |
+
assert abs(mp_low-mp_high) <= abs(fp-mp_high)
|
71 |
+
fail += mp_low != fp
|
72 |
+
assert fail < N/10
|
73 |
+
|
74 |
+
def test_bugs():
|
75 |
+
# particular bugs
|
76 |
+
assert mpf(4.4408920985006262E-16) < mpf(1.7763568394002505E-15)
|
77 |
+
assert mpf(-4.4408920985006262E-16) > mpf(-1.7763568394002505E-15)
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_convert.py
ADDED
@@ -0,0 +1,233 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import random
|
2 |
+
from mpmath import *
|
3 |
+
from mpmath.libmp import *
|
4 |
+
|
5 |
+
|
6 |
+
def test_basic_string():
|
7 |
+
"""
|
8 |
+
Test basic string conversion
|
9 |
+
"""
|
10 |
+
mp.dps = 15
|
11 |
+
assert mpf('3') == mpf('3.0') == mpf('0003.') == mpf('0.03e2') == mpf(3.0)
|
12 |
+
assert mpf('30') == mpf('30.0') == mpf('00030.') == mpf(30.0)
|
13 |
+
for i in range(10):
|
14 |
+
for j in range(10):
|
15 |
+
assert mpf('%ie%i' % (i,j)) == i * 10**j
|
16 |
+
assert str(mpf('25000.0')) == '25000.0'
|
17 |
+
assert str(mpf('2500.0')) == '2500.0'
|
18 |
+
assert str(mpf('250.0')) == '250.0'
|
19 |
+
assert str(mpf('25.0')) == '25.0'
|
20 |
+
assert str(mpf('2.5')) == '2.5'
|
21 |
+
assert str(mpf('0.25')) == '0.25'
|
22 |
+
assert str(mpf('0.025')) == '0.025'
|
23 |
+
assert str(mpf('0.0025')) == '0.0025'
|
24 |
+
assert str(mpf('0.00025')) == '0.00025'
|
25 |
+
assert str(mpf('0.000025')) == '2.5e-5'
|
26 |
+
assert str(mpf(0)) == '0.0'
|
27 |
+
assert str(mpf('2.5e1000000000000000000000')) == '2.5e+1000000000000000000000'
|
28 |
+
assert str(mpf('2.6e-1000000000000000000000')) == '2.6e-1000000000000000000000'
|
29 |
+
assert str(mpf(1.23402834e-15)) == '1.23402834e-15'
|
30 |
+
assert str(mpf(-1.23402834e-15)) == '-1.23402834e-15'
|
31 |
+
assert str(mpf(-1.2344e-15)) == '-1.2344e-15'
|
32 |
+
assert repr(mpf(-1.2344e-15)) == "mpf('-1.2343999999999999e-15')"
|
33 |
+
assert str(mpf("2163048125L")) == '2163048125.0'
|
34 |
+
assert str(mpf("-2163048125l")) == '-2163048125.0'
|
35 |
+
assert str(mpf("-2163048125L/1088391168")) == '-1.98738118113799'
|
36 |
+
assert str(mpf("2163048125/1088391168l")) == '1.98738118113799'
|
37 |
+
|
38 |
+
def test_pretty():
|
39 |
+
mp.pretty = True
|
40 |
+
assert repr(mpf(2.5)) == '2.5'
|
41 |
+
assert repr(mpc(2.5,3.5)) == '(2.5 + 3.5j)'
|
42 |
+
mp.pretty = False
|
43 |
+
iv.pretty = True
|
44 |
+
assert repr(mpi(2.5,3.5)) == '[2.5, 3.5]'
|
45 |
+
iv.pretty = False
|
46 |
+
|
47 |
+
def test_str_whitespace():
|
48 |
+
assert mpf('1.26 ') == 1.26
|
49 |
+
|
50 |
+
def test_unicode():
|
51 |
+
mp.dps = 15
|
52 |
+
try:
|
53 |
+
unicode = unicode
|
54 |
+
except NameError:
|
55 |
+
unicode = str
|
56 |
+
assert mpf(unicode('2.76')) == 2.76
|
57 |
+
assert mpf(unicode('inf')) == inf
|
58 |
+
|
59 |
+
def test_str_format():
|
60 |
+
assert to_str(from_float(0.1),15,strip_zeros=False) == '0.100000000000000'
|
61 |
+
assert to_str(from_float(0.0),15,show_zero_exponent=True) == '0.0e+0'
|
62 |
+
assert to_str(from_float(0.0),0,show_zero_exponent=True) == '.0e+0'
|
63 |
+
assert to_str(from_float(0.0),0,show_zero_exponent=False) == '.0'
|
64 |
+
assert to_str(from_float(0.0),1,show_zero_exponent=True) == '0.0e+0'
|
65 |
+
assert to_str(from_float(0.0),1,show_zero_exponent=False) == '0.0'
|
66 |
+
assert to_str(from_float(1.23),3,show_zero_exponent=True) == '1.23e+0'
|
67 |
+
assert to_str(from_float(1.23456789000000e-2),15,strip_zeros=False,min_fixed=0,max_fixed=0) == '1.23456789000000e-2'
|
68 |
+
assert to_str(from_float(1.23456789000000e+2),15,strip_zeros=False,min_fixed=0,max_fixed=0) == '1.23456789000000e+2'
|
69 |
+
assert to_str(from_float(2.1287e14), 15, max_fixed=1000) == '212870000000000.0'
|
70 |
+
assert to_str(from_float(2.1287e15), 15, max_fixed=1000) == '2128700000000000.0'
|
71 |
+
assert to_str(from_float(2.1287e16), 15, max_fixed=1000) == '21287000000000000.0'
|
72 |
+
assert to_str(from_float(2.1287e30), 15, max_fixed=1000) == '2128700000000000000000000000000.0'
|
73 |
+
|
74 |
+
def test_tight_string_conversion():
|
75 |
+
mp.dps = 15
|
76 |
+
# In an old version, '0.5' wasn't recognized as representing
|
77 |
+
# an exact binary number and was erroneously rounded up or down
|
78 |
+
assert from_str('0.5', 10, round_floor) == fhalf
|
79 |
+
assert from_str('0.5', 10, round_ceiling) == fhalf
|
80 |
+
|
81 |
+
def test_eval_repr_invariant():
|
82 |
+
"""Test that eval(repr(x)) == x"""
|
83 |
+
random.seed(123)
|
84 |
+
for dps in [10, 15, 20, 50, 100]:
|
85 |
+
mp.dps = dps
|
86 |
+
for i in range(1000):
|
87 |
+
a = mpf(random.random())**0.5 * 10**random.randint(-100, 100)
|
88 |
+
assert eval(repr(a)) == a
|
89 |
+
mp.dps = 15
|
90 |
+
|
91 |
+
def test_str_bugs():
|
92 |
+
mp.dps = 15
|
93 |
+
# Decimal rounding used to give the wrong exponent in some cases
|
94 |
+
assert str(mpf('1e600')) == '1.0e+600'
|
95 |
+
assert str(mpf('1e10000')) == '1.0e+10000'
|
96 |
+
|
97 |
+
def test_str_prec0():
|
98 |
+
assert to_str(from_float(1.234), 0) == '.0e+0'
|
99 |
+
assert to_str(from_float(1e-15), 0) == '.0e-15'
|
100 |
+
assert to_str(from_float(1e+15), 0) == '.0e+15'
|
101 |
+
assert to_str(from_float(-1e-15), 0) == '-.0e-15'
|
102 |
+
assert to_str(from_float(-1e+15), 0) == '-.0e+15'
|
103 |
+
|
104 |
+
def test_convert_rational():
|
105 |
+
mp.dps = 15
|
106 |
+
assert from_rational(30, 5, 53, round_nearest) == (0, 3, 1, 2)
|
107 |
+
assert from_rational(-7, 4, 53, round_nearest) == (1, 7, -2, 3)
|
108 |
+
assert to_rational((0, 1, -1, 1)) == (1, 2)
|
109 |
+
|
110 |
+
def test_custom_class():
|
111 |
+
class mympf:
|
112 |
+
@property
|
113 |
+
def _mpf_(self):
|
114 |
+
return mpf(3.5)._mpf_
|
115 |
+
class mympc:
|
116 |
+
@property
|
117 |
+
def _mpc_(self):
|
118 |
+
return mpf(3.5)._mpf_, mpf(2.5)._mpf_
|
119 |
+
assert mpf(2) + mympf() == 5.5
|
120 |
+
assert mympf() + mpf(2) == 5.5
|
121 |
+
assert mpf(mympf()) == 3.5
|
122 |
+
assert mympc() + mpc(2) == mpc(5.5, 2.5)
|
123 |
+
assert mpc(2) + mympc() == mpc(5.5, 2.5)
|
124 |
+
assert mpc(mympc()) == (3.5+2.5j)
|
125 |
+
|
126 |
+
def test_conversion_methods():
|
127 |
+
class SomethingRandom:
|
128 |
+
pass
|
129 |
+
class SomethingReal:
|
130 |
+
def _mpmath_(self, prec, rounding):
|
131 |
+
return mp.make_mpf(from_str('1.3', prec, rounding))
|
132 |
+
class SomethingComplex:
|
133 |
+
def _mpmath_(self, prec, rounding):
|
134 |
+
return mp.make_mpc((from_str('1.3', prec, rounding), \
|
135 |
+
from_str('1.7', prec, rounding)))
|
136 |
+
x = mpf(3)
|
137 |
+
z = mpc(3)
|
138 |
+
a = SomethingRandom()
|
139 |
+
y = SomethingReal()
|
140 |
+
w = SomethingComplex()
|
141 |
+
for d in [15, 45]:
|
142 |
+
mp.dps = d
|
143 |
+
assert (x+y).ae(mpf('4.3'))
|
144 |
+
assert (y+x).ae(mpf('4.3'))
|
145 |
+
assert (x+w).ae(mpc('4.3', '1.7'))
|
146 |
+
assert (w+x).ae(mpc('4.3', '1.7'))
|
147 |
+
assert (z+y).ae(mpc('4.3'))
|
148 |
+
assert (y+z).ae(mpc('4.3'))
|
149 |
+
assert (z+w).ae(mpc('4.3', '1.7'))
|
150 |
+
assert (w+z).ae(mpc('4.3', '1.7'))
|
151 |
+
x-y; y-x; x-w; w-x; z-y; y-z; z-w; w-z
|
152 |
+
x*y; y*x; x*w; w*x; z*y; y*z; z*w; w*z
|
153 |
+
x/y; y/x; x/w; w/x; z/y; y/z; z/w; w/z
|
154 |
+
x**y; y**x; x**w; w**x; z**y; y**z; z**w; w**z
|
155 |
+
x==y; y==x; x==w; w==x; z==y; y==z; z==w; w==z
|
156 |
+
mp.dps = 15
|
157 |
+
assert x.__add__(a) is NotImplemented
|
158 |
+
assert x.__radd__(a) is NotImplemented
|
159 |
+
assert x.__lt__(a) is NotImplemented
|
160 |
+
assert x.__gt__(a) is NotImplemented
|
161 |
+
assert x.__le__(a) is NotImplemented
|
162 |
+
assert x.__ge__(a) is NotImplemented
|
163 |
+
assert x.__eq__(a) is NotImplemented
|
164 |
+
assert x.__ne__(a) is NotImplemented
|
165 |
+
# implementation detail
|
166 |
+
if hasattr(x, "__cmp__"):
|
167 |
+
assert x.__cmp__(a) is NotImplemented
|
168 |
+
assert x.__sub__(a) is NotImplemented
|
169 |
+
assert x.__rsub__(a) is NotImplemented
|
170 |
+
assert x.__mul__(a) is NotImplemented
|
171 |
+
assert x.__rmul__(a) is NotImplemented
|
172 |
+
assert x.__div__(a) is NotImplemented
|
173 |
+
assert x.__rdiv__(a) is NotImplemented
|
174 |
+
assert x.__mod__(a) is NotImplemented
|
175 |
+
assert x.__rmod__(a) is NotImplemented
|
176 |
+
assert x.__pow__(a) is NotImplemented
|
177 |
+
assert x.__rpow__(a) is NotImplemented
|
178 |
+
assert z.__add__(a) is NotImplemented
|
179 |
+
assert z.__radd__(a) is NotImplemented
|
180 |
+
assert z.__eq__(a) is NotImplemented
|
181 |
+
assert z.__ne__(a) is NotImplemented
|
182 |
+
assert z.__sub__(a) is NotImplemented
|
183 |
+
assert z.__rsub__(a) is NotImplemented
|
184 |
+
assert z.__mul__(a) is NotImplemented
|
185 |
+
assert z.__rmul__(a) is NotImplemented
|
186 |
+
assert z.__div__(a) is NotImplemented
|
187 |
+
assert z.__rdiv__(a) is NotImplemented
|
188 |
+
assert z.__pow__(a) is NotImplemented
|
189 |
+
assert z.__rpow__(a) is NotImplemented
|
190 |
+
|
191 |
+
def test_mpmathify():
|
192 |
+
assert mpmathify('1/2') == 0.5
|
193 |
+
assert mpmathify('(1.0+1.0j)') == mpc(1, 1)
|
194 |
+
assert mpmathify('(1.2e-10 - 3.4e5j)') == mpc('1.2e-10', '-3.4e5')
|
195 |
+
assert mpmathify('1j') == mpc(1j)
|
196 |
+
|
197 |
+
def test_issue548():
|
198 |
+
try:
|
199 |
+
# This expression is invalid, but may trigger the ReDOS vulnerability
|
200 |
+
# in the regular expression for parsing complex numbers.
|
201 |
+
mpmathify('(' + '1' * 5000 + '!j')
|
202 |
+
except:
|
203 |
+
return
|
204 |
+
# The expression is invalid and should raise an exception.
|
205 |
+
assert False
|
206 |
+
|
207 |
+
def test_compatibility():
|
208 |
+
try:
|
209 |
+
import numpy as np
|
210 |
+
from fractions import Fraction
|
211 |
+
from decimal import Decimal
|
212 |
+
import decimal
|
213 |
+
except ImportError:
|
214 |
+
return
|
215 |
+
# numpy types
|
216 |
+
for nptype in np.core.numerictypes.typeDict.values():
|
217 |
+
if issubclass(nptype, np.complexfloating):
|
218 |
+
x = nptype(complex(0.5, -0.5))
|
219 |
+
elif issubclass(nptype, np.floating):
|
220 |
+
x = nptype(0.5)
|
221 |
+
elif issubclass(nptype, np.integer):
|
222 |
+
x = nptype(2)
|
223 |
+
# Handle the weird types
|
224 |
+
try: diff = np.abs(type(np.sqrt(x))(sqrt(x)) - np.sqrt(x))
|
225 |
+
except: continue
|
226 |
+
assert diff < 2.0**-53
|
227 |
+
#Fraction and Decimal
|
228 |
+
oldprec = mp.prec
|
229 |
+
mp.prec = 1000
|
230 |
+
decimal.getcontext().prec = mp.dps
|
231 |
+
assert sqrt(Fraction(2, 3)).ae(sqrt(mpf('2/3')))
|
232 |
+
assert sqrt(Decimal(2)/Decimal(3)).ae(sqrt(mpf('2/3')))
|
233 |
+
mp.prec = oldprec
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_diff.py
ADDED
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from mpmath import *
|
2 |
+
|
3 |
+
def test_diff():
|
4 |
+
mp.dps = 15
|
5 |
+
assert diff(log, 2.0, n=0).ae(log(2))
|
6 |
+
assert diff(cos, 1.0).ae(-sin(1))
|
7 |
+
assert diff(abs, 0.0) == 0
|
8 |
+
assert diff(abs, 0.0, direction=1) == 1
|
9 |
+
assert diff(abs, 0.0, direction=-1) == -1
|
10 |
+
assert diff(exp, 1.0).ae(e)
|
11 |
+
assert diff(exp, 1.0, n=5).ae(e)
|
12 |
+
assert diff(exp, 2.0, n=5, direction=3*j).ae(e**2)
|
13 |
+
assert diff(lambda x: x**2, 3.0, method='quad').ae(6)
|
14 |
+
assert diff(lambda x: 3+x**5, 3.0, n=2, method='quad').ae(540)
|
15 |
+
assert diff(lambda x: 3+x**5, 3.0, n=2, method='step').ae(540)
|
16 |
+
assert diffun(sin)(2).ae(cos(2))
|
17 |
+
assert diffun(sin, n=2)(2).ae(-sin(2))
|
18 |
+
|
19 |
+
def test_diffs():
|
20 |
+
mp.dps = 15
|
21 |
+
assert [chop(d) for d in diffs(sin, 0, 1)] == [0, 1]
|
22 |
+
assert [chop(d) for d in diffs(sin, 0, 1, method='quad')] == [0, 1]
|
23 |
+
assert [chop(d) for d in diffs(sin, 0, 2)] == [0, 1, 0]
|
24 |
+
assert [chop(d) for d in diffs(sin, 0, 2, method='quad')] == [0, 1, 0]
|
25 |
+
|
26 |
+
def test_taylor():
|
27 |
+
mp.dps = 15
|
28 |
+
# Easy to test since the coefficients are exact in floating-point
|
29 |
+
assert taylor(sqrt, 1, 4) == [1, 0.5, -0.125, 0.0625, -0.0390625]
|
30 |
+
|
31 |
+
def test_diff_partial():
|
32 |
+
mp.dps = 15
|
33 |
+
x,y,z = xyz = 2,3,7
|
34 |
+
f = lambda x,y,z: 3*x**2 * (y+2)**3 * z**5
|
35 |
+
assert diff(f, xyz, (0,0,0)).ae(25210500)
|
36 |
+
assert diff(f, xyz, (0,0,1)).ae(18007500)
|
37 |
+
assert diff(f, xyz, (0,0,2)).ae(10290000)
|
38 |
+
assert diff(f, xyz, (0,1,0)).ae(15126300)
|
39 |
+
assert diff(f, xyz, (0,1,1)).ae(10804500)
|
40 |
+
assert diff(f, xyz, (0,1,2)).ae(6174000)
|
41 |
+
assert diff(f, xyz, (0,2,0)).ae(6050520)
|
42 |
+
assert diff(f, xyz, (0,2,1)).ae(4321800)
|
43 |
+
assert diff(f, xyz, (0,2,2)).ae(2469600)
|
44 |
+
assert diff(f, xyz, (1,0,0)).ae(25210500)
|
45 |
+
assert diff(f, xyz, (1,0,1)).ae(18007500)
|
46 |
+
assert diff(f, xyz, (1,0,2)).ae(10290000)
|
47 |
+
assert diff(f, xyz, (1,1,0)).ae(15126300)
|
48 |
+
assert diff(f, xyz, (1,1,1)).ae(10804500)
|
49 |
+
assert diff(f, xyz, (1,1,2)).ae(6174000)
|
50 |
+
assert diff(f, xyz, (1,2,0)).ae(6050520)
|
51 |
+
assert diff(f, xyz, (1,2,1)).ae(4321800)
|
52 |
+
assert diff(f, xyz, (1,2,2)).ae(2469600)
|
53 |
+
assert diff(f, xyz, (2,0,0)).ae(12605250)
|
54 |
+
assert diff(f, xyz, (2,0,1)).ae(9003750)
|
55 |
+
assert diff(f, xyz, (2,0,2)).ae(5145000)
|
56 |
+
assert diff(f, xyz, (2,1,0)).ae(7563150)
|
57 |
+
assert diff(f, xyz, (2,1,1)).ae(5402250)
|
58 |
+
assert diff(f, xyz, (2,1,2)).ae(3087000)
|
59 |
+
assert diff(f, xyz, (2,2,0)).ae(3025260)
|
60 |
+
assert diff(f, xyz, (2,2,1)).ae(2160900)
|
61 |
+
assert diff(f, xyz, (2,2,2)).ae(1234800)
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_division.py
ADDED
@@ -0,0 +1,143 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from mpmath.libmp import *
|
2 |
+
from mpmath import mpf, mp
|
3 |
+
|
4 |
+
from random import randint, choice, seed
|
5 |
+
|
6 |
+
all_modes = [round_floor, round_ceiling, round_down, round_up, round_nearest]
|
7 |
+
|
8 |
+
fb = from_bstr
|
9 |
+
fi = from_int
|
10 |
+
ff = from_float
|
11 |
+
|
12 |
+
|
13 |
+
def test_div_1_3():
|
14 |
+
a = fi(1)
|
15 |
+
b = fi(3)
|
16 |
+
c = fi(-1)
|
17 |
+
|
18 |
+
# floor rounds down, ceiling rounds up
|
19 |
+
assert mpf_div(a, b, 7, round_floor) == fb('0.01010101')
|
20 |
+
assert mpf_div(a, b, 7, round_ceiling) == fb('0.01010110')
|
21 |
+
assert mpf_div(a, b, 7, round_down) == fb('0.01010101')
|
22 |
+
assert mpf_div(a, b, 7, round_up) == fb('0.01010110')
|
23 |
+
assert mpf_div(a, b, 7, round_nearest) == fb('0.01010101')
|
24 |
+
|
25 |
+
# floor rounds up, ceiling rounds down
|
26 |
+
assert mpf_div(c, b, 7, round_floor) == fb('-0.01010110')
|
27 |
+
assert mpf_div(c, b, 7, round_ceiling) == fb('-0.01010101')
|
28 |
+
assert mpf_div(c, b, 7, round_down) == fb('-0.01010101')
|
29 |
+
assert mpf_div(c, b, 7, round_up) == fb('-0.01010110')
|
30 |
+
assert mpf_div(c, b, 7, round_nearest) == fb('-0.01010101')
|
31 |
+
|
32 |
+
def test_mpf_divi_1_3():
|
33 |
+
a = 1
|
34 |
+
b = fi(3)
|
35 |
+
c = -1
|
36 |
+
assert mpf_rdiv_int(a, b, 7, round_floor) == fb('0.01010101')
|
37 |
+
assert mpf_rdiv_int(a, b, 7, round_ceiling) == fb('0.01010110')
|
38 |
+
assert mpf_rdiv_int(a, b, 7, round_down) == fb('0.01010101')
|
39 |
+
assert mpf_rdiv_int(a, b, 7, round_up) == fb('0.01010110')
|
40 |
+
assert mpf_rdiv_int(a, b, 7, round_nearest) == fb('0.01010101')
|
41 |
+
assert mpf_rdiv_int(c, b, 7, round_floor) == fb('-0.01010110')
|
42 |
+
assert mpf_rdiv_int(c, b, 7, round_ceiling) == fb('-0.01010101')
|
43 |
+
assert mpf_rdiv_int(c, b, 7, round_down) == fb('-0.01010101')
|
44 |
+
assert mpf_rdiv_int(c, b, 7, round_up) == fb('-0.01010110')
|
45 |
+
assert mpf_rdiv_int(c, b, 7, round_nearest) == fb('-0.01010101')
|
46 |
+
|
47 |
+
|
48 |
+
def test_div_300():
|
49 |
+
|
50 |
+
q = fi(1000000)
|
51 |
+
a = fi(300499999) # a/q is a little less than a half-integer
|
52 |
+
b = fi(300500000) # b/q exactly a half-integer
|
53 |
+
c = fi(300500001) # c/q is a little more than a half-integer
|
54 |
+
|
55 |
+
# Check nearest integer rounding (prec=9 as 2**8 < 300 < 2**9)
|
56 |
+
|
57 |
+
assert mpf_div(a, q, 9, round_down) == fi(300)
|
58 |
+
assert mpf_div(b, q, 9, round_down) == fi(300)
|
59 |
+
assert mpf_div(c, q, 9, round_down) == fi(300)
|
60 |
+
assert mpf_div(a, q, 9, round_up) == fi(301)
|
61 |
+
assert mpf_div(b, q, 9, round_up) == fi(301)
|
62 |
+
assert mpf_div(c, q, 9, round_up) == fi(301)
|
63 |
+
|
64 |
+
# Nearest even integer is down
|
65 |
+
assert mpf_div(a, q, 9, round_nearest) == fi(300)
|
66 |
+
assert mpf_div(b, q, 9, round_nearest) == fi(300)
|
67 |
+
assert mpf_div(c, q, 9, round_nearest) == fi(301)
|
68 |
+
|
69 |
+
# Nearest even integer is up
|
70 |
+
a = fi(301499999)
|
71 |
+
b = fi(301500000)
|
72 |
+
c = fi(301500001)
|
73 |
+
assert mpf_div(a, q, 9, round_nearest) == fi(301)
|
74 |
+
assert mpf_div(b, q, 9, round_nearest) == fi(302)
|
75 |
+
assert mpf_div(c, q, 9, round_nearest) == fi(302)
|
76 |
+
|
77 |
+
|
78 |
+
def test_tight_integer_division():
|
79 |
+
# Test that integer division at tightest possible precision is exact
|
80 |
+
N = 100
|
81 |
+
seed(1)
|
82 |
+
for i in range(N):
|
83 |
+
a = choice([1, -1]) * randint(1, 1<<randint(10, 100))
|
84 |
+
b = choice([1, -1]) * randint(1, 1<<randint(10, 100))
|
85 |
+
p = a * b
|
86 |
+
width = bitcount(abs(b)) - trailing(b)
|
87 |
+
a = fi(a); b = fi(b); p = fi(p)
|
88 |
+
for mode in all_modes:
|
89 |
+
assert mpf_div(p, a, width, mode) == b
|
90 |
+
|
91 |
+
|
92 |
+
def test_epsilon_rounding():
|
93 |
+
# Verify that mpf_div uses infinite precision; this result will
|
94 |
+
# appear to be exactly 0.101 to a near-sighted algorithm
|
95 |
+
|
96 |
+
a = fb('0.101' + ('0'*200) + '1')
|
97 |
+
b = fb('1.10101')
|
98 |
+
c = mpf_mul(a, b, 250, round_floor) # exact
|
99 |
+
assert mpf_div(c, b, bitcount(a[1]), round_floor) == a # exact
|
100 |
+
|
101 |
+
assert mpf_div(c, b, 2, round_down) == fb('0.10')
|
102 |
+
assert mpf_div(c, b, 3, round_down) == fb('0.101')
|
103 |
+
assert mpf_div(c, b, 2, round_up) == fb('0.11')
|
104 |
+
assert mpf_div(c, b, 3, round_up) == fb('0.110')
|
105 |
+
assert mpf_div(c, b, 2, round_floor) == fb('0.10')
|
106 |
+
assert mpf_div(c, b, 3, round_floor) == fb('0.101')
|
107 |
+
assert mpf_div(c, b, 2, round_ceiling) == fb('0.11')
|
108 |
+
assert mpf_div(c, b, 3, round_ceiling) == fb('0.110')
|
109 |
+
|
110 |
+
# The same for negative numbers
|
111 |
+
a = fb('-0.101' + ('0'*200) + '1')
|
112 |
+
b = fb('1.10101')
|
113 |
+
c = mpf_mul(a, b, 250, round_floor)
|
114 |
+
assert mpf_div(c, b, bitcount(a[1]), round_floor) == a
|
115 |
+
|
116 |
+
assert mpf_div(c, b, 2, round_down) == fb('-0.10')
|
117 |
+
assert mpf_div(c, b, 3, round_up) == fb('-0.110')
|
118 |
+
|
119 |
+
# Floor goes up, ceiling goes down
|
120 |
+
assert mpf_div(c, b, 2, round_floor) == fb('-0.11')
|
121 |
+
assert mpf_div(c, b, 3, round_floor) == fb('-0.110')
|
122 |
+
assert mpf_div(c, b, 2, round_ceiling) == fb('-0.10')
|
123 |
+
assert mpf_div(c, b, 3, round_ceiling) == fb('-0.101')
|
124 |
+
|
125 |
+
|
126 |
+
def test_mod():
|
127 |
+
mp.dps = 15
|
128 |
+
assert mpf(234) % 1 == 0
|
129 |
+
assert mpf(-3) % 256 == 253
|
130 |
+
assert mpf(0.25) % 23490.5 == 0.25
|
131 |
+
assert mpf(0.25) % -23490.5 == -23490.25
|
132 |
+
assert mpf(-0.25) % 23490.5 == 23490.25
|
133 |
+
assert mpf(-0.25) % -23490.5 == -0.25
|
134 |
+
# Check that these cases are handled efficiently
|
135 |
+
assert mpf('1e10000000000') % 1 == 0
|
136 |
+
assert mpf('1.23e-1000000000') % 1 == mpf('1.23e-1000000000')
|
137 |
+
# test __rmod__
|
138 |
+
assert 3 % mpf('1.75') == 1.25
|
139 |
+
|
140 |
+
def test_div_negative_rnd_bug():
|
141 |
+
mp.dps = 15
|
142 |
+
assert (-3) / mpf('0.1531879017645047') == mpf('-19.583791966887116')
|
143 |
+
assert mpf('-2.6342475750861301') / mpf('0.35126216427941814') == mpf('-7.4993775104985909')
|
env-llmeval/lib/python3.10/site-packages/mpmath/tests/test_eigen.py
ADDED
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/usr/bin/python
|
2 |
+
# -*- coding: utf-8 -*-
|
3 |
+
|
4 |
+
from mpmath import mp
|
5 |
+
from mpmath import libmp
|
6 |
+
|
7 |
+
xrange = libmp.backend.xrange
|
8 |
+
|
9 |
+
def run_hessenberg(A, verbose = 0):
|
10 |
+
if verbose > 1:
|
11 |
+
print("original matrix (hessenberg):\n", A)
|
12 |
+
|
13 |
+
n = A.rows
|
14 |
+
|
15 |
+
Q, H = mp.hessenberg(A)
|
16 |
+
|
17 |
+
if verbose > 1:
|
18 |
+
print("Q:\n",Q)
|
19 |
+
print("H:\n",H)
|
20 |
+
|
21 |
+
B = Q * H * Q.transpose_conj()
|
22 |
+
|
23 |
+
eps = mp.exp(0.8 * mp.log(mp.eps))
|
24 |
+
|
25 |
+
err0 = 0
|
26 |
+
for x in xrange(n):
|
27 |
+
for y in xrange(n):
|
28 |
+
err0 += abs(A[y,x] - B[y,x])
|
29 |
+
err0 /= n * n
|
30 |
+
|
31 |
+
err1 = 0
|
32 |
+
for x in xrange(n):
|
33 |
+
for y in xrange(x + 2, n):
|
34 |
+
err1 += abs(H[y,x])
|
35 |
+
|
36 |
+
if verbose > 0:
|
37 |
+
print("difference (H):", err0, err1)
|
38 |
+
|
39 |
+
if verbose > 1:
|
40 |
+
print("B:\n", B)
|
41 |
+
|
42 |
+
assert err0 < eps
|
43 |
+
assert err1 == 0
|
44 |
+
|
45 |
+
|
46 |
+
def run_schur(A, verbose = 0):
|
47 |
+
if verbose > 1:
|
48 |
+
print("original matrix (schur):\n", A)
|
49 |
+
|
50 |
+
n = A.rows
|
51 |
+
|
52 |
+
Q, R = mp.schur(A)
|
53 |
+
|
54 |
+
if verbose > 1:
|
55 |
+
print("Q:\n", Q)
|
56 |
+
print("R:\n", R)
|
57 |
+
|
58 |
+
B = Q * R * Q.transpose_conj()
|
59 |
+
C = Q * Q.transpose_conj()
|
60 |
+
|
61 |
+
eps = mp.exp(0.8 * mp.log(mp.eps))
|
62 |
+
|
63 |
+
err0 = 0
|
64 |
+
for x in xrange(n):
|
65 |
+
for y in xrange(n):
|
66 |
+
err0 += abs(A[y,x] - B[y,x])
|
67 |
+
err0 /= n * n
|
68 |
+
|
69 |
+
err1 = 0
|
70 |
+
for x in xrange(n):
|
71 |
+
for y in xrange(n):
|
72 |
+
if x == y:
|
73 |
+
C[y,x] -= 1
|
74 |
+
err1 += abs(C[y,x])
|
75 |
+
err1 /= n * n
|
76 |
+
|
77 |
+
err2 = 0
|
78 |
+
for x in xrange(n):
|
79 |
+
for y in xrange(x + 1, n):
|
80 |
+
err2 += abs(R[y,x])
|
81 |
+
|
82 |
+
if verbose > 0:
|
83 |
+
print("difference (S):", err0, err1, err2)
|
84 |
+
|
85 |
+
if verbose > 1:
|
86 |
+
print("B:\n", B)
|
87 |
+
|
88 |
+
assert err0 < eps
|
89 |
+
assert err1 < eps
|
90 |
+
assert err2 == 0
|
91 |
+
|
92 |
+
def run_eig(A, verbose = 0):
|
93 |
+
if verbose > 1:
|
94 |
+
print("original matrix (eig):\n", A)
|
95 |
+
|
96 |
+
n = A.rows
|
97 |
+
|
98 |
+
E, EL, ER = mp.eig(A, left = True, right = True)
|
99 |
+
|
100 |
+
if verbose > 1:
|
101 |
+
print("E:\n", E)
|
102 |
+
print("EL:\n", EL)
|
103 |
+
print("ER:\n", ER)
|
104 |
+
|
105 |
+
eps = mp.exp(0.8 * mp.log(mp.eps))
|
106 |
+
|
107 |
+
err0 = 0
|
108 |
+
for i in xrange(n):
|
109 |
+
B = A * ER[:,i] - E[i] * ER[:,i]
|
110 |
+
err0 = max(err0, mp.mnorm(B))
|
111 |
+
|
112 |
+
B = EL[i,:] * A - EL[i,:] * E[i]
|
113 |
+
err0 = max(err0, mp.mnorm(B))
|
114 |
+
|
115 |
+
err0 /= n * n
|
116 |
+
|
117 |
+
if verbose > 0:
|
118 |
+
print("difference (E):", err0)
|
119 |
+
|
120 |
+
assert err0 < eps
|
121 |
+
|
122 |
+
#####################
|
123 |
+
|
124 |
+
def test_eig_dyn():
|
125 |
+
v = 0
|
126 |
+
for i in xrange(5):
|
127 |
+
n = 1 + int(mp.rand() * 5)
|
128 |
+
if mp.rand() > 0.5:
|
129 |
+
# real
|
130 |
+
A = 2 * mp.randmatrix(n, n) - 1
|
131 |
+
if mp.rand() > 0.5:
|
132 |
+
A *= 10
|
133 |
+
for x in xrange(n):
|
134 |
+
for y in xrange(n):
|
135 |
+
A[x,y] = int(A[x,y])
|
136 |
+
else:
|
137 |
+
A = (2 * mp.randmatrix(n, n) - 1) + 1j * (2 * mp.randmatrix(n, n) - 1)
|
138 |
+
if mp.rand() > 0.5:
|
139 |
+
A *= 10
|
140 |
+
for x in xrange(n):
|
141 |
+
for y in xrange(n):
|
142 |
+
A[x,y] = int(mp.re(A[x,y])) + 1j * int(mp.im(A[x,y]))
|
143 |
+
|
144 |
+
run_hessenberg(A, verbose = v)
|
145 |
+
run_schur(A, verbose = v)
|
146 |
+
run_eig(A, verbose = v)
|
147 |
+
|
148 |
+
def test_eig():
|
149 |
+
v = 0
|
150 |
+
AS = []
|
151 |
+
|
152 |
+
A = mp.matrix([[2, 1, 0], # jordan block of size 3
|
153 |
+
[0, 2, 1],
|
154 |
+
[0, 0, 2]])
|
155 |
+
AS.append(A)
|
156 |
+
AS.append(A.transpose())
|
157 |
+
|
158 |
+
A = mp.matrix([[2, 0, 0], # jordan block of size 2
|
159 |
+
[0, 2, 1],
|
160 |
+
[0, 0, 2]])
|
161 |
+
AS.append(A)
|
162 |
+
AS.append(A.transpose())
|
163 |
+
|
164 |
+
A = mp.matrix([[2, 0, 1], # jordan block of size 2
|
165 |
+
[0, 2, 0],
|
166 |
+
[0, 0, 2]])
|
167 |
+
AS.append(A)
|
168 |
+
AS.append(A.transpose())
|
169 |
+
|
170 |
+
A= mp.matrix([[0, 0, 1], # cyclic
|
171 |
+
[1, 0, 0],
|
172 |
+
[0, 1, 0]])
|
173 |
+
AS.append(A)
|
174 |
+
AS.append(A.transpose())
|
175 |
+
|
176 |
+
for A in AS:
|
177 |
+
run_hessenberg(A, verbose = v)
|
178 |
+
run_schur(A, verbose = v)
|
179 |
+
run_eig(A, verbose = v)
|