evalf.py 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808
  1. """
  2. Adaptive numerical evaluation of SymPy expressions, using mpmath
  3. for mathematical functions.
  4. """
  5. from __future__ import annotations
  6. from typing import Callable, TYPE_CHECKING, Any, overload, Type
  7. import math
  8. import mpmath.libmp as libmp
  9. from mpmath import (
  10. make_mpc, make_mpf, mp, mpc, mpf, nsum, quadts, quadosc, workprec)
  11. from mpmath import inf as mpmath_inf
  12. from mpmath.libmp import (from_int, from_man_exp, from_rational, fhalf,
  13. fnan, finf, fninf, fnone, fone, fzero, mpf_abs, mpf_add,
  14. mpf_atan, mpf_atan2, mpf_cmp, mpf_cos, mpf_e, mpf_exp, mpf_log, mpf_lt,
  15. mpf_mul, mpf_neg, mpf_pi, mpf_pow, mpf_pow_int, mpf_shift, mpf_sin,
  16. mpf_sqrt, normalize, round_nearest, to_int, to_str, mpf_tan)
  17. from mpmath.libmp import bitcount as mpmath_bitcount
  18. from mpmath.libmp.backend import MPZ
  19. from mpmath.libmp.libmpc import _infs_nan
  20. from mpmath.libmp.libmpf import dps_to_prec, prec_to_dps
  21. from .sympify import sympify
  22. from .singleton import S
  23. from sympy.external.gmpy import SYMPY_INTS
  24. from sympy.utilities.iterables import is_sequence
  25. from sympy.utilities.lambdify import lambdify
  26. from sympy.utilities.misc import as_int
  27. if TYPE_CHECKING:
  28. from sympy.core.expr import Expr
  29. from sympy.core.add import Add
  30. from sympy.core.mul import Mul
  31. from sympy.core.power import Pow
  32. from sympy.core.symbol import Symbol
  33. from sympy.integrals.integrals import Integral
  34. from sympy.concrete.summations import Sum
  35. from sympy.concrete.products import Product
  36. from sympy.functions.elementary.exponential import exp, log
  37. from sympy.functions.elementary.complexes import Abs, re, im
  38. from sympy.functions.elementary.integers import ceiling, floor
  39. from sympy.functions.elementary.trigonometric import atan
  40. from .numbers import Float, Rational, Integer, AlgebraicNumber, Number
  41. LG10 = math.log2(10)
  42. rnd = round_nearest
  43. def bitcount(n):
  44. """Return smallest integer, b, such that |n|/2**b < 1.
  45. """
  46. return mpmath_bitcount(abs(int(n)))
  47. # Used in a few places as placeholder values to denote exponents and
  48. # precision levels, e.g. of exact numbers. Must be careful to avoid
  49. # passing these to mpmath functions or returning them in final results.
  50. INF = float(mpmath_inf)
  51. MINUS_INF = float(-mpmath_inf)
  52. # ~= 100 digits. Real men set this to INF.
  53. DEFAULT_MAXPREC = 333
  54. class PrecisionExhausted(ArithmeticError):
  55. pass
  56. #----------------------------------------------------------------------------#
  57. # #
  58. # Helper functions for arithmetic and complex parts #
  59. # #
  60. #----------------------------------------------------------------------------#
  61. """
  62. An mpf value tuple is a tuple of integers (sign, man, exp, bc)
  63. representing a floating-point number: [1, -1][sign]*man*2**exp where
  64. sign is 0 or 1 and bc should correspond to the number of bits used to
  65. represent the mantissa (man) in binary notation, e.g.
  66. """
  67. MPF_TUP = tuple[int, int, int, int] # mpf value tuple
  68. """
  69. Explanation
  70. ===========
  71. >>> from sympy.core.evalf import bitcount
  72. >>> sign, man, exp, bc = 0, 5, 1, 3
  73. >>> n = [1, -1][sign]*man*2**exp
  74. >>> n, bitcount(man)
  75. (10, 3)
  76. A temporary result is a tuple (re, im, re_acc, im_acc) where
  77. re and im are nonzero mpf value tuples representing approximate
  78. numbers, or None to denote exact zeros.
  79. re_acc, im_acc are integers denoting log2(e) where e is the estimated
  80. relative accuracy of the respective complex part, but may be anything
  81. if the corresponding complex part is None.
  82. """
  83. TMP_RES = Any # temporary result, should be some variant of
  84. # tUnion[tTuple[Optional[MPF_TUP], Optional[MPF_TUP],
  85. # Optional[int], Optional[int]],
  86. # 'ComplexInfinity']
  87. # but mypy reports error because it doesn't know as we know
  88. # 1. re and re_acc are either both None or both MPF_TUP
  89. # 2. sometimes the result can't be zoo
  90. # type of the "options" parameter in internal evalf functions
  91. OPT_DICT = dict[str, Any]
  92. def fastlog(x: MPF_TUP | None) -> int | Any:
  93. """Fast approximation of log2(x) for an mpf value tuple x.
  94. Explanation
  95. ===========
  96. Calculated as exponent + width of mantissa. This is an
  97. approximation for two reasons: 1) it gives the ceil(log2(abs(x)))
  98. value and 2) it is too high by 1 in the case that x is an exact
  99. power of 2. Although this is easy to remedy by testing to see if
  100. the odd mpf mantissa is 1 (indicating that one was dealing with
  101. an exact power of 2) that would decrease the speed and is not
  102. necessary as this is only being used as an approximation for the
  103. number of bits in x. The correct return value could be written as
  104. "x[2] + (x[3] if x[1] != 1 else 0)".
  105. Since mpf tuples always have an odd mantissa, no check is done
  106. to see if the mantissa is a multiple of 2 (in which case the
  107. result would be too large by 1).
  108. Examples
  109. ========
  110. >>> from sympy import log
  111. >>> from sympy.core.evalf import fastlog, bitcount
  112. >>> s, m, e = 0, 5, 1
  113. >>> bc = bitcount(m)
  114. >>> n = [1, -1][s]*m*2**e
  115. >>> n, (log(n)/log(2)).evalf(2), fastlog((s, m, e, bc))
  116. (10, 3.3, 4)
  117. """
  118. if not x or x == fzero:
  119. return MINUS_INF
  120. return x[2] + x[3]
  121. def pure_complex(v: Expr, or_real=False) -> tuple[Number, Number] | None:
  122. """Return a and b if v matches a + I*b where b is not zero and
  123. a and b are Numbers, else None. If `or_real` is True then 0 will
  124. be returned for `b` if `v` is a real number.
  125. Examples
  126. ========
  127. >>> from sympy.core.evalf import pure_complex
  128. >>> from sympy import sqrt, I, S
  129. >>> a, b, surd = S(2), S(3), sqrt(2)
  130. >>> pure_complex(a)
  131. >>> pure_complex(a, or_real=True)
  132. (2, 0)
  133. >>> pure_complex(surd)
  134. >>> pure_complex(a + b*I)
  135. (2, 3)
  136. >>> pure_complex(I)
  137. (0, 1)
  138. """
  139. h, t = v.as_coeff_Add()
  140. if t:
  141. c, i = t.as_coeff_Mul()
  142. if i is S.ImaginaryUnit:
  143. return h, c
  144. elif or_real:
  145. return h, S.Zero
  146. return None
  147. # I don't know what this is, see function scaled_zero below
  148. SCALED_ZERO_TUP = tuple[list[int], int, int, int]
  149. @overload
  150. def scaled_zero(mag: SCALED_ZERO_TUP, sign=1) -> MPF_TUP:
  151. ...
  152. @overload
  153. def scaled_zero(mag: int, sign=1) -> tuple[SCALED_ZERO_TUP, int]:
  154. ...
  155. def scaled_zero(mag: SCALED_ZERO_TUP | int, sign=1) -> \
  156. MPF_TUP | tuple[SCALED_ZERO_TUP, int]:
  157. """Return an mpf representing a power of two with magnitude ``mag``
  158. and -1 for precision. Or, if ``mag`` is a scaled_zero tuple, then just
  159. remove the sign from within the list that it was initially wrapped
  160. in.
  161. Examples
  162. ========
  163. >>> from sympy.core.evalf import scaled_zero
  164. >>> from sympy import Float
  165. >>> z, p = scaled_zero(100)
  166. >>> z, p
  167. (([0], 1, 100, 1), -1)
  168. >>> ok = scaled_zero(z)
  169. >>> ok
  170. (0, 1, 100, 1)
  171. >>> Float(ok)
  172. 1.26765060022823e+30
  173. >>> Float(ok, p)
  174. 0.e+30
  175. >>> ok, p = scaled_zero(100, -1)
  176. >>> Float(scaled_zero(ok), p)
  177. -0.e+30
  178. """
  179. if isinstance(mag, tuple) and len(mag) == 4 and iszero(mag, scaled=True):
  180. return (mag[0][0],) + mag[1:]
  181. elif isinstance(mag, SYMPY_INTS):
  182. if sign not in [-1, 1]:
  183. raise ValueError('sign must be +/-1')
  184. rv, p = mpf_shift(fone, mag), -1
  185. s = 0 if sign == 1 else 1
  186. rv = ([s],) + rv[1:]
  187. return rv, p
  188. else:
  189. raise ValueError('scaled zero expects int or scaled_zero tuple.')
  190. def iszero(mpf: MPF_TUP | SCALED_ZERO_TUP | None, scaled=False) -> bool | None:
  191. if not scaled:
  192. return not mpf or not mpf[1] and not mpf[-1]
  193. return mpf and isinstance(mpf[0], list) and mpf[1] == mpf[-1] == 1
  194. def complex_accuracy(result: TMP_RES) -> int | Any:
  195. """
  196. Returns relative accuracy of a complex number with given accuracies
  197. for the real and imaginary parts. The relative accuracy is defined
  198. in the complex norm sense as ||z|+|error|| / |z| where error
  199. is equal to (real absolute error) + (imag absolute error)*i.
  200. The full expression for the (logarithmic) error can be approximated
  201. easily by using the max norm to approximate the complex norm.
  202. In the worst case (re and im equal), this is wrong by a factor
  203. sqrt(2), or by log2(sqrt(2)) = 0.5 bit.
  204. """
  205. if result is S.ComplexInfinity:
  206. return INF
  207. re, im, re_acc, im_acc = result
  208. if not im:
  209. if not re:
  210. return INF
  211. return re_acc
  212. if not re:
  213. return im_acc
  214. re_size = fastlog(re)
  215. im_size = fastlog(im)
  216. absolute_error = max(re_size - re_acc, im_size - im_acc)
  217. relative_error = absolute_error - max(re_size, im_size)
  218. return -relative_error
  219. def get_abs(expr: Expr, prec: int, options: OPT_DICT) -> TMP_RES:
  220. result = evalf(expr, prec + 2, options)
  221. if result is S.ComplexInfinity:
  222. return finf, None, prec, None
  223. re, im, re_acc, im_acc = result
  224. if not re:
  225. re, re_acc, im, im_acc = im, im_acc, re, re_acc
  226. if im:
  227. if expr.is_number:
  228. abs_expr, _, acc, _ = evalf(abs(N(expr, prec + 2)),
  229. prec + 2, options)
  230. return abs_expr, None, acc, None
  231. else:
  232. if 'subs' in options:
  233. return libmp.mpc_abs((re, im), prec), None, re_acc, None
  234. return abs(expr), None, prec, None
  235. elif re:
  236. return mpf_abs(re), None, re_acc, None
  237. else:
  238. return None, None, None, None
  239. def get_complex_part(expr: Expr, no: int, prec: int, options: OPT_DICT) -> TMP_RES:
  240. """no = 0 for real part, no = 1 for imaginary part"""
  241. workprec = prec
  242. i = 0
  243. while 1:
  244. res = evalf(expr, workprec, options)
  245. if res is S.ComplexInfinity:
  246. return fnan, None, prec, None
  247. value, accuracy = res[no::2]
  248. # XXX is the last one correct? Consider re((1+I)**2).n()
  249. if (not value) or accuracy >= prec or -value[2] > prec:
  250. return value, None, accuracy, None
  251. workprec += max(30, 2**i)
  252. i += 1
  253. def evalf_abs(expr: 'Abs', prec: int, options: OPT_DICT) -> TMP_RES:
  254. return get_abs(expr.args[0], prec, options)
  255. def evalf_re(expr: 're', prec: int, options: OPT_DICT) -> TMP_RES:
  256. return get_complex_part(expr.args[0], 0, prec, options)
  257. def evalf_im(expr: 'im', prec: int, options: OPT_DICT) -> TMP_RES:
  258. return get_complex_part(expr.args[0], 1, prec, options)
  259. def finalize_complex(re: MPF_TUP, im: MPF_TUP, prec: int) -> TMP_RES:
  260. if re == fzero and im == fzero:
  261. raise ValueError("got complex zero with unknown accuracy")
  262. elif re == fzero:
  263. return None, im, None, prec
  264. elif im == fzero:
  265. return re, None, prec, None
  266. size_re = fastlog(re)
  267. size_im = fastlog(im)
  268. if size_re > size_im:
  269. re_acc = prec
  270. im_acc = prec + min(-(size_re - size_im), 0)
  271. else:
  272. im_acc = prec
  273. re_acc = prec + min(-(size_im - size_re), 0)
  274. return re, im, re_acc, im_acc
  275. def chop_parts(value: TMP_RES, prec: int) -> TMP_RES:
  276. """
  277. Chop off tiny real or complex parts.
  278. """
  279. if value is S.ComplexInfinity:
  280. return value
  281. re, im, re_acc, im_acc = value
  282. # Method 1: chop based on absolute value
  283. if re and re not in _infs_nan and (fastlog(re) < -prec + 4):
  284. re, re_acc = None, None
  285. if im and im not in _infs_nan and (fastlog(im) < -prec + 4):
  286. im, im_acc = None, None
  287. # Method 2: chop if inaccurate and relatively small
  288. if re and im:
  289. delta = fastlog(re) - fastlog(im)
  290. if re_acc < 2 and (delta - re_acc <= -prec + 4):
  291. re, re_acc = None, None
  292. if im_acc < 2 and (delta - im_acc >= prec - 4):
  293. im, im_acc = None, None
  294. return re, im, re_acc, im_acc
  295. def check_target(expr: Expr, result: TMP_RES, prec: int):
  296. a = complex_accuracy(result)
  297. if a < prec:
  298. raise PrecisionExhausted("Failed to distinguish the expression: \n\n%s\n\n"
  299. "from zero. Try simplifying the input, using chop=True, or providing "
  300. "a higher maxn for evalf" % (expr))
  301. def get_integer_part(expr: Expr, no: int, options: OPT_DICT, return_ints=False) -> \
  302. TMP_RES | tuple[int, int]:
  303. """
  304. With no = 1, computes ceiling(expr)
  305. With no = -1, computes floor(expr)
  306. Note: this function either gives the exact result or signals failure.
  307. """
  308. from sympy.functions.elementary.complexes import re, im
  309. # The expression is likely less than 2^30 or so
  310. assumed_size = 30
  311. result = evalf(expr, assumed_size, options)
  312. if result is S.ComplexInfinity:
  313. raise ValueError("Cannot get integer part of Complex Infinity")
  314. ire, iim, ire_acc, iim_acc = result
  315. # We now know the size, so we can calculate how much extra precision
  316. # (if any) is needed to get within the nearest integer
  317. if ire and iim:
  318. gap = max(fastlog(ire) - ire_acc, fastlog(iim) - iim_acc)
  319. elif ire:
  320. gap = fastlog(ire) - ire_acc
  321. elif iim:
  322. gap = fastlog(iim) - iim_acc
  323. else:
  324. # ... or maybe the expression was exactly zero
  325. if return_ints:
  326. return 0, 0
  327. else:
  328. return None, None, None, None
  329. margin = 10
  330. if gap >= -margin:
  331. prec = margin + assumed_size + gap
  332. ire, iim, ire_acc, iim_acc = evalf(
  333. expr, prec, options)
  334. else:
  335. prec = assumed_size
  336. # We can now easily find the nearest integer, but to find floor/ceil, we
  337. # must also calculate whether the difference to the nearest integer is
  338. # positive or negative (which may fail if very close).
  339. def calc_part(re_im: Expr, nexpr: MPF_TUP):
  340. from .add import Add
  341. _, _, exponent, _ = nexpr
  342. is_int = exponent == 0
  343. nint = int(to_int(nexpr, rnd))
  344. if is_int:
  345. # make sure that we had enough precision to distinguish
  346. # between nint and the re or im part (re_im) of expr that
  347. # was passed to calc_part
  348. ire, iim, ire_acc, iim_acc = evalf(
  349. re_im - nint, 10, options) # don't need much precision
  350. assert not iim
  351. size = -fastlog(ire) + 2 # -ve b/c ire is less than 1
  352. if size > prec:
  353. ire, iim, ire_acc, iim_acc = evalf(
  354. re_im, size, options)
  355. assert not iim
  356. nexpr = ire
  357. nint = int(to_int(nexpr, rnd))
  358. _, _, new_exp, _ = ire
  359. is_int = new_exp == 0
  360. if not is_int:
  361. # if there are subs and they all contain integer re/im parts
  362. # then we can (hopefully) safely substitute them into the
  363. # expression
  364. s = options.get('subs', False)
  365. if s:
  366. # use strict=False with as_int because we take
  367. # 2.0 == 2
  368. def is_int_reim(x):
  369. """Check for integer or integer + I*integer."""
  370. try:
  371. as_int(x, strict=False)
  372. return True
  373. except ValueError:
  374. try:
  375. [as_int(i, strict=False) for i in x.as_real_imag()]
  376. return True
  377. except ValueError:
  378. return False
  379. if all(is_int_reim(v) for v in s.values()):
  380. re_im = re_im.subs(s)
  381. re_im = Add(re_im, -nint, evaluate=False)
  382. x, _, x_acc, _ = evalf(re_im, 10, options)
  383. try:
  384. check_target(re_im, (x, None, x_acc, None), 3)
  385. except PrecisionExhausted:
  386. if not re_im.equals(0):
  387. raise PrecisionExhausted
  388. x = fzero
  389. nint += int(no*(mpf_cmp(x or fzero, fzero) == no))
  390. nint = from_int(nint)
  391. return nint, INF
  392. re_, im_, re_acc, im_acc = None, None, None, None
  393. if ire is not None and ire != fzero:
  394. re_, re_acc = calc_part(re(expr, evaluate=False), ire)
  395. if iim is not None and iim != fzero:
  396. im_, im_acc = calc_part(im(expr, evaluate=False), iim)
  397. if return_ints:
  398. return int(to_int(re_ or fzero)), int(to_int(im_ or fzero))
  399. return re_, im_, re_acc, im_acc
  400. def evalf_ceiling(expr: 'ceiling', prec: int, options: OPT_DICT) -> TMP_RES:
  401. return get_integer_part(expr.args[0], 1, options)
  402. def evalf_floor(expr: 'floor', prec: int, options: OPT_DICT) -> TMP_RES:
  403. return get_integer_part(expr.args[0], -1, options)
  404. def evalf_float(expr: 'Float', prec: int, options: OPT_DICT) -> TMP_RES:
  405. return expr._mpf_, None, prec, None
  406. def evalf_rational(expr: 'Rational', prec: int, options: OPT_DICT) -> TMP_RES:
  407. return from_rational(expr.p, expr.q, prec), None, prec, None
  408. def evalf_integer(expr: 'Integer', prec: int, options: OPT_DICT) -> TMP_RES:
  409. return from_int(expr.p, prec), None, prec, None
  410. #----------------------------------------------------------------------------#
  411. # #
  412. # Arithmetic operations #
  413. # #
  414. #----------------------------------------------------------------------------#
  415. def add_terms(terms: list, prec: int, target_prec: int) -> \
  416. tuple[MPF_TUP | SCALED_ZERO_TUP | None, int | None]:
  417. """
  418. Helper for evalf_add. Adds a list of (mpfval, accuracy) terms.
  419. Returns
  420. =======
  421. - None, None if there are no non-zero terms;
  422. - terms[0] if there is only 1 term;
  423. - scaled_zero if the sum of the terms produces a zero by cancellation
  424. e.g. mpfs representing 1 and -1 would produce a scaled zero which need
  425. special handling since they are not actually zero and they are purposely
  426. malformed to ensure that they cannot be used in anything but accuracy
  427. calculations;
  428. - a tuple that is scaled to target_prec that corresponds to the
  429. sum of the terms.
  430. The returned mpf tuple will be normalized to target_prec; the input
  431. prec is used to define the working precision.
  432. XXX explain why this is needed and why one cannot just loop using mpf_add
  433. """
  434. terms = [t for t in terms if not iszero(t[0])]
  435. if not terms:
  436. return None, None
  437. elif len(terms) == 1:
  438. return terms[0]
  439. # see if any argument is NaN or oo and thus warrants a special return
  440. special = []
  441. from .numbers import Float
  442. for t in terms:
  443. arg = Float._new(t[0], 1)
  444. if arg is S.NaN or arg.is_infinite:
  445. special.append(arg)
  446. if special:
  447. from .add import Add
  448. rv = evalf(Add(*special), prec + 4, {})
  449. return rv[0], rv[2]
  450. working_prec = 2*prec
  451. sum_man, sum_exp = 0, 0
  452. absolute_err: list[int] = []
  453. for x, accuracy in terms:
  454. sign, man, exp, bc = x
  455. if sign:
  456. man = -man
  457. absolute_err.append(bc + exp - accuracy)
  458. delta = exp - sum_exp
  459. if exp >= sum_exp:
  460. # x much larger than existing sum?
  461. # first: quick test
  462. if ((delta > working_prec) and
  463. ((not sum_man) or
  464. delta - bitcount(abs(sum_man)) > working_prec)):
  465. sum_man = man
  466. sum_exp = exp
  467. else:
  468. sum_man += (man << delta)
  469. else:
  470. delta = -delta
  471. # x much smaller than existing sum?
  472. if delta - bc > working_prec:
  473. if not sum_man:
  474. sum_man, sum_exp = man, exp
  475. else:
  476. sum_man = (sum_man << delta) + man
  477. sum_exp = exp
  478. absolute_error = max(absolute_err)
  479. if not sum_man:
  480. return scaled_zero(absolute_error)
  481. if sum_man < 0:
  482. sum_sign = 1
  483. sum_man = -sum_man
  484. else:
  485. sum_sign = 0
  486. sum_bc = bitcount(sum_man)
  487. sum_accuracy = sum_exp + sum_bc - absolute_error
  488. r = normalize(sum_sign, sum_man, sum_exp, sum_bc, target_prec,
  489. rnd), sum_accuracy
  490. return r
  491. def evalf_add(v: 'Add', prec: int, options: OPT_DICT) -> TMP_RES:
  492. res = pure_complex(v)
  493. if res:
  494. h, c = res
  495. re, _, re_acc, _ = evalf(h, prec, options)
  496. im, _, im_acc, _ = evalf(c, prec, options)
  497. return re, im, re_acc, im_acc
  498. oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC)
  499. i = 0
  500. target_prec = prec
  501. while 1:
  502. options['maxprec'] = min(oldmaxprec, 2*prec)
  503. terms = [evalf(arg, prec + 10, options) for arg in v.args]
  504. n = terms.count(S.ComplexInfinity)
  505. if n >= 2:
  506. return fnan, None, prec, None
  507. re, re_acc = add_terms(
  508. [a[0::2] for a in terms if isinstance(a, tuple) and a[0]], prec, target_prec)
  509. im, im_acc = add_terms(
  510. [a[1::2] for a in terms if isinstance(a, tuple) and a[1]], prec, target_prec)
  511. if n == 1:
  512. if re in (finf, fninf, fnan) or im in (finf, fninf, fnan):
  513. return fnan, None, prec, None
  514. return S.ComplexInfinity
  515. acc = complex_accuracy((re, im, re_acc, im_acc))
  516. if acc >= target_prec:
  517. if options.get('verbose'):
  518. print("ADD: wanted", target_prec, "accurate bits, got", re_acc, im_acc)
  519. break
  520. else:
  521. if (prec - target_prec) > options['maxprec']:
  522. break
  523. prec = prec + max(10 + 2**i, target_prec - acc)
  524. i += 1
  525. if options.get('verbose'):
  526. print("ADD: restarting with prec", prec)
  527. options['maxprec'] = oldmaxprec
  528. if iszero(re, scaled=True):
  529. re = scaled_zero(re)
  530. if iszero(im, scaled=True):
  531. im = scaled_zero(im)
  532. return re, im, re_acc, im_acc
  533. def evalf_mul(v: 'Mul', prec: int, options: OPT_DICT) -> TMP_RES:
  534. res = pure_complex(v)
  535. if res:
  536. # the only pure complex that is a mul is h*I
  537. _, h = res
  538. im, _, im_acc, _ = evalf(h, prec, options)
  539. return None, im, None, im_acc
  540. args = list(v.args)
  541. # see if any argument is NaN or oo and thus warrants a special return
  542. has_zero = False
  543. special = []
  544. from .numbers import Float
  545. for arg in args:
  546. result = evalf(arg, prec, options)
  547. if result is S.ComplexInfinity:
  548. special.append(result)
  549. continue
  550. if result[0] is None:
  551. if result[1] is None:
  552. has_zero = True
  553. continue
  554. num = Float._new(result[0], 1)
  555. if num is S.NaN:
  556. return fnan, None, prec, None
  557. if num.is_infinite:
  558. special.append(num)
  559. if special:
  560. if has_zero:
  561. return fnan, None, prec, None
  562. from .mul import Mul
  563. return evalf(Mul(*special), prec + 4, {})
  564. if has_zero:
  565. return None, None, None, None
  566. # With guard digits, multiplication in the real case does not destroy
  567. # accuracy. This is also true in the complex case when considering the
  568. # total accuracy; however accuracy for the real or imaginary parts
  569. # separately may be lower.
  570. acc = prec
  571. # XXX: big overestimate
  572. working_prec = prec + len(args) + 5
  573. # Empty product is 1
  574. start = man, exp, bc = MPZ(1), 0, 1
  575. # First, we multiply all pure real or pure imaginary numbers.
  576. # direction tells us that the result should be multiplied by
  577. # I**direction; all other numbers get put into complex_factors
  578. # to be multiplied out after the first phase.
  579. last = len(args)
  580. direction = 0
  581. args.append(S.One)
  582. complex_factors = []
  583. for i, arg in enumerate(args):
  584. if i != last and pure_complex(arg):
  585. args[-1] = (args[-1]*arg).expand()
  586. continue
  587. elif i == last and arg is S.One:
  588. continue
  589. re, im, re_acc, im_acc = evalf(arg, working_prec, options)
  590. if re and im:
  591. complex_factors.append((re, im, re_acc, im_acc))
  592. continue
  593. elif re:
  594. (s, m, e, b), w_acc = re, re_acc
  595. elif im:
  596. (s, m, e, b), w_acc = im, im_acc
  597. direction += 1
  598. else:
  599. return None, None, None, None
  600. direction += 2*s
  601. man *= m
  602. exp += e
  603. bc += b
  604. while bc > 3*working_prec:
  605. man >>= working_prec
  606. exp += working_prec
  607. bc -= working_prec
  608. acc = min(acc, w_acc)
  609. sign = (direction & 2) >> 1
  610. if not complex_factors:
  611. v = normalize(sign, man, exp, bitcount(man), prec, rnd)
  612. # multiply by i
  613. if direction & 1:
  614. return None, v, None, acc
  615. else:
  616. return v, None, acc, None
  617. else:
  618. # initialize with the first term
  619. if (man, exp, bc) != start:
  620. # there was a real part; give it an imaginary part
  621. re, im = (sign, man, exp, bitcount(man)), (0, MPZ(0), 0, 0)
  622. i0 = 0
  623. else:
  624. # there is no real part to start (other than the starting 1)
  625. wre, wim, wre_acc, wim_acc = complex_factors[0]
  626. acc = min(acc,
  627. complex_accuracy((wre, wim, wre_acc, wim_acc)))
  628. re = wre
  629. im = wim
  630. i0 = 1
  631. for wre, wim, wre_acc, wim_acc in complex_factors[i0:]:
  632. # acc is the overall accuracy of the product; we aren't
  633. # computing exact accuracies of the product.
  634. acc = min(acc,
  635. complex_accuracy((wre, wim, wre_acc, wim_acc)))
  636. use_prec = working_prec
  637. A = mpf_mul(re, wre, use_prec)
  638. B = mpf_mul(mpf_neg(im), wim, use_prec)
  639. C = mpf_mul(re, wim, use_prec)
  640. D = mpf_mul(im, wre, use_prec)
  641. re = mpf_add(A, B, use_prec)
  642. im = mpf_add(C, D, use_prec)
  643. if options.get('verbose'):
  644. print("MUL: wanted", prec, "accurate bits, got", acc)
  645. # multiply by I
  646. if direction & 1:
  647. re, im = mpf_neg(im), re
  648. return re, im, acc, acc
  649. def evalf_pow(v: 'Pow', prec: int, options) -> TMP_RES:
  650. target_prec = prec
  651. base, exp = v.args
  652. # We handle x**n separately. This has two purposes: 1) it is much
  653. # faster, because we avoid calling evalf on the exponent, and 2) it
  654. # allows better handling of real/imaginary parts that are exactly zero
  655. if exp.is_Integer:
  656. p: int = exp.p # type: ignore
  657. # Exact
  658. if not p:
  659. return fone, None, prec, None
  660. # Exponentiation by p magnifies relative error by |p|, so the
  661. # base must be evaluated with increased precision if p is large
  662. prec += int(math.log2(abs(p)))
  663. result = evalf(base, prec + 5, options)
  664. if result is S.ComplexInfinity:
  665. if p < 0:
  666. return None, None, None, None
  667. return result
  668. re, im, re_acc, im_acc = result
  669. # Real to integer power
  670. if re and not im:
  671. return mpf_pow_int(re, p, target_prec), None, target_prec, None
  672. # (x*I)**n = I**n * x**n
  673. if im and not re:
  674. z = mpf_pow_int(im, p, target_prec)
  675. case = p % 4
  676. if case == 0:
  677. return z, None, target_prec, None
  678. if case == 1:
  679. return None, z, None, target_prec
  680. if case == 2:
  681. return mpf_neg(z), None, target_prec, None
  682. if case == 3:
  683. return None, mpf_neg(z), None, target_prec
  684. # Zero raised to an integer power
  685. if not re:
  686. if p < 0:
  687. return S.ComplexInfinity
  688. return None, None, None, None
  689. # General complex number to arbitrary integer power
  690. re, im = libmp.mpc_pow_int((re, im), p, prec)
  691. # Assumes full accuracy in input
  692. return finalize_complex(re, im, target_prec)
  693. result = evalf(base, prec + 5, options)
  694. if result is S.ComplexInfinity:
  695. if exp.is_Rational:
  696. if exp < 0:
  697. return None, None, None, None
  698. return result
  699. raise NotImplementedError
  700. # Pure square root
  701. if exp is S.Half:
  702. xre, xim, _, _ = result
  703. # General complex square root
  704. if xim:
  705. re, im = libmp.mpc_sqrt((xre or fzero, xim), prec)
  706. return finalize_complex(re, im, prec)
  707. if not xre:
  708. return None, None, None, None
  709. # Square root of a negative real number
  710. if mpf_lt(xre, fzero):
  711. return None, mpf_sqrt(mpf_neg(xre), prec), None, prec
  712. # Positive square root
  713. return mpf_sqrt(xre, prec), None, prec, None
  714. # We first evaluate the exponent to find its magnitude
  715. # This determines the working precision that must be used
  716. prec += 10
  717. result = evalf(exp, prec, options)
  718. if result is S.ComplexInfinity:
  719. return fnan, None, prec, None
  720. yre, yim, _, _ = result
  721. # Special cases: x**0
  722. if not (yre or yim):
  723. return fone, None, prec, None
  724. ysize = fastlog(yre)
  725. # Restart if too big
  726. # XXX: prec + ysize might exceed maxprec
  727. if ysize > 5:
  728. prec += ysize
  729. yre, yim, _, _ = evalf(exp, prec, options)
  730. # Pure exponential function; no need to evalf the base
  731. if base is S.Exp1:
  732. if yim:
  733. re, im = libmp.mpc_exp((yre or fzero, yim), prec)
  734. return finalize_complex(re, im, target_prec)
  735. return mpf_exp(yre, target_prec), None, target_prec, None
  736. xre, xim, _, _ = evalf(base, prec + 5, options)
  737. # 0**y
  738. if not (xre or xim):
  739. if yim:
  740. return fnan, None, prec, None
  741. if yre[0] == 1: # y < 0
  742. return S.ComplexInfinity
  743. return None, None, None, None
  744. # (real ** complex) or (complex ** complex)
  745. if yim:
  746. re, im = libmp.mpc_pow(
  747. (xre or fzero, xim or fzero), (yre or fzero, yim),
  748. target_prec)
  749. return finalize_complex(re, im, target_prec)
  750. # complex ** real
  751. if xim:
  752. re, im = libmp.mpc_pow_mpf((xre or fzero, xim), yre, target_prec)
  753. return finalize_complex(re, im, target_prec)
  754. # negative ** real
  755. elif mpf_lt(xre, fzero):
  756. re, im = libmp.mpc_pow_mpf((xre, fzero), yre, target_prec)
  757. return finalize_complex(re, im, target_prec)
  758. # positive ** real
  759. else:
  760. return mpf_pow(xre, yre, target_prec), None, target_prec, None
  761. #----------------------------------------------------------------------------#
  762. # #
  763. # Special functions #
  764. # #
  765. #----------------------------------------------------------------------------#
  766. def evalf_exp(expr: 'exp', prec: int, options: OPT_DICT) -> TMP_RES:
  767. from .power import Pow
  768. return evalf_pow(Pow(S.Exp1, expr.exp, evaluate=False), prec, options)
  769. def evalf_trig(v: Expr, prec: int, options: OPT_DICT) -> TMP_RES:
  770. """
  771. This function handles sin , cos and tan of complex arguments.
  772. """
  773. from sympy.functions.elementary.trigonometric import cos, sin, tan
  774. if isinstance(v, cos):
  775. func = mpf_cos
  776. elif isinstance(v, sin):
  777. func = mpf_sin
  778. elif isinstance(v,tan):
  779. func = mpf_tan
  780. else:
  781. raise NotImplementedError
  782. arg = v.args[0]
  783. # 20 extra bits is possibly overkill. It does make the need
  784. # to restart very unlikely
  785. xprec = prec + 20
  786. re, im, re_acc, im_acc = evalf(arg, xprec, options)
  787. if im:
  788. if 'subs' in options:
  789. v = v.subs(options['subs'])
  790. return evalf(v._eval_evalf(prec), prec, options)
  791. if not re:
  792. if isinstance(v, cos):
  793. return fone, None, prec, None
  794. elif isinstance(v, sin):
  795. return None, None, None, None
  796. elif isinstance(v,tan):
  797. return None, None, None, None
  798. else:
  799. raise NotImplementedError
  800. # For trigonometric functions, we are interested in the
  801. # fixed-point (absolute) accuracy of the argument.
  802. xsize = fastlog(re)
  803. # Magnitude <= 1.0. OK to compute directly, because there is no
  804. # danger of hitting the first root of cos (with sin, magnitude
  805. # <= 2.0 would actually be ok)
  806. if xsize < 1:
  807. return func(re, prec, rnd), None, prec, None
  808. # Very large
  809. if xsize >= 10:
  810. xprec = prec + xsize
  811. re, im, re_acc, im_acc = evalf(arg, xprec, options)
  812. # Need to repeat in case the argument is very close to a
  813. # multiple of pi (or pi/2), hitting close to a root
  814. while 1:
  815. y = func(re, prec, rnd)
  816. ysize = fastlog(y)
  817. gap = -ysize
  818. accuracy = (xprec - xsize) - gap
  819. if accuracy < prec:
  820. if options.get('verbose'):
  821. print("SIN/COS/TAN", accuracy, "wanted", prec, "gap", gap)
  822. print(to_str(y, 10))
  823. if xprec > options.get('maxprec', DEFAULT_MAXPREC):
  824. return y, None, accuracy, None
  825. xprec += gap
  826. re, im, re_acc, im_acc = evalf(arg, xprec, options)
  827. continue
  828. else:
  829. return y, None, prec, None
  830. def evalf_log(expr: 'log', prec: int, options: OPT_DICT) -> TMP_RES:
  831. if len(expr.args)>1:
  832. expr = expr.doit()
  833. return evalf(expr, prec, options)
  834. arg = expr.args[0]
  835. workprec = prec + 10
  836. result = evalf(arg, workprec, options)
  837. if result is S.ComplexInfinity:
  838. return result
  839. xre, xim, xacc, _ = result
  840. # evalf can return NoneTypes if chop=True
  841. # issue 18516, 19623
  842. if xre is xim is None:
  843. # Dear reviewer, I do not know what -inf is;
  844. # it looks to be (1, 0, -789, -3)
  845. # but I'm not sure in general,
  846. # so we just let mpmath figure
  847. # it out by taking log of 0 directly.
  848. # It would be better to return -inf instead.
  849. xre = fzero
  850. if xim:
  851. from sympy.functions.elementary.complexes import Abs
  852. from sympy.functions.elementary.exponential import log
  853. # XXX: use get_abs etc instead
  854. re = evalf_log(
  855. log(Abs(arg, evaluate=False), evaluate=False), prec, options)
  856. im = mpf_atan2(xim, xre or fzero, prec)
  857. return re[0], im, re[2], prec
  858. imaginary_term = (mpf_cmp(xre, fzero) < 0)
  859. re = mpf_log(mpf_abs(xre), prec, rnd)
  860. size = fastlog(re)
  861. if prec - size > workprec and re != fzero:
  862. from .add import Add
  863. # We actually need to compute 1+x accurately, not x
  864. add = Add(S.NegativeOne, arg, evaluate=False)
  865. xre, xim, _, _ = evalf_add(add, prec, options)
  866. prec2 = workprec - fastlog(xre)
  867. # xre is now x - 1 so we add 1 back here to calculate x
  868. re = mpf_log(mpf_abs(mpf_add(xre, fone, prec2)), prec, rnd)
  869. re_acc = prec
  870. if imaginary_term:
  871. return re, mpf_pi(prec), re_acc, prec
  872. else:
  873. return re, None, re_acc, None
  874. def evalf_atan(v: 'atan', prec: int, options: OPT_DICT) -> TMP_RES:
  875. arg = v.args[0]
  876. xre, xim, reacc, imacc = evalf(arg, prec + 5, options)
  877. if xre is xim is None:
  878. return (None,)*4
  879. if xim:
  880. raise NotImplementedError
  881. return mpf_atan(xre, prec, rnd), None, prec, None
  882. def evalf_subs(prec: int, subs: dict) -> dict:
  883. """ Change all Float entries in `subs` to have precision prec. """
  884. newsubs = {}
  885. for a, b in subs.items():
  886. b = S(b)
  887. if b.is_Float:
  888. b = b._eval_evalf(prec)
  889. newsubs[a] = b
  890. return newsubs
  891. def evalf_piecewise(expr: Expr, prec: int, options: OPT_DICT) -> TMP_RES:
  892. from .numbers import Float, Integer
  893. if 'subs' in options:
  894. expr = expr.subs(evalf_subs(prec, options['subs']))
  895. newopts = options.copy()
  896. del newopts['subs']
  897. if hasattr(expr, 'func'):
  898. return evalf(expr, prec, newopts)
  899. if isinstance(expr, float):
  900. return evalf(Float(expr), prec, newopts)
  901. if isinstance(expr, int):
  902. return evalf(Integer(expr), prec, newopts)
  903. # We still have undefined symbols
  904. raise NotImplementedError
  905. def evalf_alg_num(a: 'AlgebraicNumber', prec: int, options: OPT_DICT) -> TMP_RES:
  906. return evalf(a.to_root(), prec, options)
  907. #----------------------------------------------------------------------------#
  908. # #
  909. # High-level operations #
  910. # #
  911. #----------------------------------------------------------------------------#
  912. def as_mpmath(x: Any, prec: int, options: OPT_DICT) -> mpc | mpf:
  913. from .numbers import Infinity, NegativeInfinity, Zero
  914. x = sympify(x)
  915. if isinstance(x, Zero) or x == 0.0:
  916. return mpf(0)
  917. if isinstance(x, Infinity):
  918. return mpf('inf')
  919. if isinstance(x, NegativeInfinity):
  920. return mpf('-inf')
  921. # XXX
  922. result = evalf(x, prec, options)
  923. return quad_to_mpmath(result)
  924. def do_integral(expr: 'Integral', prec: int, options: OPT_DICT) -> TMP_RES:
  925. func = expr.args[0]
  926. x, xlow, xhigh = expr.args[1]
  927. if xlow == xhigh:
  928. xlow = xhigh = 0
  929. elif x not in func.free_symbols:
  930. # only the difference in limits matters in this case
  931. # so if there is a symbol in common that will cancel
  932. # out when taking the difference, then use that
  933. # difference
  934. if xhigh.free_symbols & xlow.free_symbols:
  935. diff = xhigh - xlow
  936. if diff.is_number:
  937. xlow, xhigh = 0, diff
  938. oldmaxprec = options.get('maxprec', DEFAULT_MAXPREC)
  939. options['maxprec'] = min(oldmaxprec, 2*prec)
  940. with workprec(prec + 5):
  941. xlow = as_mpmath(xlow, prec + 15, options)
  942. xhigh = as_mpmath(xhigh, prec + 15, options)
  943. # Integration is like summation, and we can phone home from
  944. # the integrand function to update accuracy summation style
  945. # Note that this accuracy is inaccurate, since it fails
  946. # to account for the variable quadrature weights,
  947. # but it is better than nothing
  948. from sympy.functions.elementary.trigonometric import cos, sin
  949. from .symbol import Wild
  950. have_part = [False, False]
  951. max_real_term: float | int = MINUS_INF
  952. max_imag_term: float | int = MINUS_INF
  953. def f(t: Expr) -> mpc | mpf:
  954. nonlocal max_real_term, max_imag_term
  955. re, im, re_acc, im_acc = evalf(func, mp.prec, {'subs': {x: t}})
  956. have_part[0] = re or have_part[0]
  957. have_part[1] = im or have_part[1]
  958. max_real_term = max(max_real_term, fastlog(re))
  959. max_imag_term = max(max_imag_term, fastlog(im))
  960. if im:
  961. return mpc(re or fzero, im)
  962. return mpf(re or fzero)
  963. if options.get('quad') == 'osc':
  964. A = Wild('A', exclude=[x])
  965. B = Wild('B', exclude=[x])
  966. D = Wild('D')
  967. m = func.match(cos(A*x + B)*D)
  968. if not m:
  969. m = func.match(sin(A*x + B)*D)
  970. if not m:
  971. raise ValueError("An integrand of the form sin(A*x+B)*f(x) "
  972. "or cos(A*x+B)*f(x) is required for oscillatory quadrature")
  973. period = as_mpmath(2*S.Pi/m[A], prec + 15, options)
  974. result = quadosc(f, [xlow, xhigh], period=period)
  975. # XXX: quadosc does not do error detection yet
  976. quadrature_error = MINUS_INF
  977. else:
  978. result, quadrature_err = quadts(f, [xlow, xhigh], error=1)
  979. quadrature_error = fastlog(quadrature_err._mpf_)
  980. options['maxprec'] = oldmaxprec
  981. if have_part[0]:
  982. re: MPF_TUP | None = result.real._mpf_
  983. re_acc: int | None
  984. if re == fzero:
  985. re_s, re_acc = scaled_zero(int(-max(prec, max_real_term, quadrature_error)))
  986. re = scaled_zero(re_s) # handled ok in evalf_integral
  987. else:
  988. re_acc = int(-max(max_real_term - fastlog(re) - prec, quadrature_error))
  989. else:
  990. re, re_acc = None, None
  991. if have_part[1]:
  992. im: MPF_TUP | None = result.imag._mpf_
  993. im_acc: int | None
  994. if im == fzero:
  995. im_s, im_acc = scaled_zero(int(-max(prec, max_imag_term, quadrature_error)))
  996. im = scaled_zero(im_s) # handled ok in evalf_integral
  997. else:
  998. im_acc = int(-max(max_imag_term - fastlog(im) - prec, quadrature_error))
  999. else:
  1000. im, im_acc = None, None
  1001. result = re, im, re_acc, im_acc
  1002. return result
  1003. def evalf_integral(expr: 'Integral', prec: int, options: OPT_DICT) -> TMP_RES:
  1004. limits = expr.limits
  1005. if len(limits) != 1 or len(limits[0]) != 3:
  1006. raise NotImplementedError
  1007. workprec = prec
  1008. i = 0
  1009. maxprec = options.get('maxprec', INF)
  1010. while 1:
  1011. result = do_integral(expr, workprec, options)
  1012. accuracy = complex_accuracy(result)
  1013. if accuracy >= prec: # achieved desired precision
  1014. break
  1015. if workprec >= maxprec: # can't increase accuracy any more
  1016. break
  1017. if accuracy == -1:
  1018. # maybe the answer really is zero and maybe we just haven't increased
  1019. # the precision enough. So increase by doubling to not take too long
  1020. # to get to maxprec.
  1021. workprec *= 2
  1022. else:
  1023. workprec += max(prec, 2**i)
  1024. workprec = min(workprec, maxprec)
  1025. i += 1
  1026. return result
  1027. def check_convergence(numer: Expr, denom: Expr, n: Symbol) -> tuple[int, Any, Any]:
  1028. """
  1029. Returns
  1030. =======
  1031. (h, g, p) where
  1032. -- h is:
  1033. > 0 for convergence of rate 1/factorial(n)**h
  1034. < 0 for divergence of rate factorial(n)**(-h)
  1035. = 0 for geometric or polynomial convergence or divergence
  1036. -- abs(g) is:
  1037. > 1 for geometric convergence of rate 1/h**n
  1038. < 1 for geometric divergence of rate h**n
  1039. = 1 for polynomial convergence or divergence
  1040. (g < 0 indicates an alternating series)
  1041. -- p is:
  1042. > 1 for polynomial convergence of rate 1/n**h
  1043. <= 1 for polynomial divergence of rate n**(-h)
  1044. """
  1045. from sympy.polys.polytools import Poly
  1046. npol = Poly(numer, n)
  1047. dpol = Poly(denom, n)
  1048. p = npol.degree()
  1049. q = dpol.degree()
  1050. rate = q - p
  1051. if rate:
  1052. return rate, None, None
  1053. constant = dpol.LC() / npol.LC()
  1054. from .numbers import equal_valued
  1055. if not equal_valued(abs(constant), 1):
  1056. return rate, constant, None
  1057. if npol.degree() == dpol.degree() == 0:
  1058. return rate, constant, 0
  1059. pc = npol.all_coeffs()[1]
  1060. qc = dpol.all_coeffs()[1]
  1061. return rate, constant, (qc - pc)/dpol.LC()
  1062. def hypsum(expr: Expr, n: Symbol, start: int, prec: int) -> mpf:
  1063. """
  1064. Sum a rapidly convergent infinite hypergeometric series with
  1065. given general term, e.g. e = hypsum(1/factorial(n), n). The
  1066. quotient between successive terms must be a quotient of integer
  1067. polynomials.
  1068. """
  1069. from .numbers import Float, equal_valued
  1070. from sympy.simplify.simplify import hypersimp
  1071. if prec == float('inf'):
  1072. raise NotImplementedError('does not support inf prec')
  1073. if start:
  1074. expr = expr.subs(n, n + start)
  1075. hs = hypersimp(expr, n)
  1076. if hs is None:
  1077. raise NotImplementedError("a hypergeometric series is required")
  1078. num, den = hs.as_numer_denom()
  1079. func1 = lambdify(n, num)
  1080. func2 = lambdify(n, den)
  1081. h, g, p = check_convergence(num, den, n)
  1082. if h < 0:
  1083. raise ValueError("Sum diverges like (n!)^%i" % (-h))
  1084. eterm = expr.subs(n, 0)
  1085. if not eterm.is_Rational:
  1086. raise NotImplementedError("Non rational term functionality is not implemented.")
  1087. term: Rational = eterm # type: ignore
  1088. # Direct summation if geometric or faster
  1089. if h > 0 or (h == 0 and abs(g) > 1):
  1090. term = (MPZ(term.p) << prec) // term.q
  1091. s = term
  1092. k = 1
  1093. while abs(term) > 5:
  1094. term *= MPZ(func1(k - 1))
  1095. term //= MPZ(func2(k - 1))
  1096. s += term
  1097. k += 1
  1098. return from_man_exp(s, -prec)
  1099. else:
  1100. alt = g < 0
  1101. if abs(g) < 1:
  1102. raise ValueError("Sum diverges like (%i)^n" % abs(1/g))
  1103. if p < 1 or (equal_valued(p, 1) and not alt):
  1104. raise ValueError("Sum diverges like n^%i" % (-p))
  1105. # We have polynomial convergence: use Richardson extrapolation
  1106. vold = None
  1107. ndig = prec_to_dps(prec)
  1108. while True:
  1109. # Need to use at least quad precision because a lot of cancellation
  1110. # might occur in the extrapolation process; we check the answer to
  1111. # make sure that the desired precision has been reached, too.
  1112. prec2 = 4*prec
  1113. term0 = (MPZ(term.p) << prec2) // term.q
  1114. def summand(k, _term=[term0]):
  1115. if k:
  1116. k = int(k)
  1117. _term[0] *= MPZ(func1(k - 1))
  1118. _term[0] //= MPZ(func2(k - 1))
  1119. return make_mpf(from_man_exp(_term[0], -prec2))
  1120. with workprec(prec):
  1121. v = nsum(summand, [0, mpmath_inf], method='richardson')
  1122. vf = Float(v, ndig)
  1123. if vold is not None and vold == vf:
  1124. break
  1125. prec += prec # double precision each time
  1126. vold = vf
  1127. return v._mpf_
  1128. def evalf_prod(expr: 'Product', prec: int, options: OPT_DICT) -> TMP_RES:
  1129. if all((l[1] - l[2]).is_Integer for l in expr.limits):
  1130. result = evalf(expr.doit(), prec=prec, options=options)
  1131. else:
  1132. from sympy.concrete.summations import Sum
  1133. result = evalf(expr.rewrite(Sum), prec=prec, options=options)
  1134. return result
  1135. def evalf_sum(expr: 'Sum', prec: int, options: OPT_DICT) -> TMP_RES:
  1136. from .numbers import Float
  1137. if 'subs' in options:
  1138. expr = expr.subs(options['subs']) # type: ignore
  1139. func = expr.function
  1140. limits = expr.limits
  1141. if len(limits) != 1 or len(limits[0]) != 3:
  1142. raise NotImplementedError
  1143. if func.is_zero:
  1144. return None, None, prec, None
  1145. prec2 = prec + 10
  1146. try:
  1147. n, a, b = limits[0]
  1148. if b is not S.Infinity or a is S.NegativeInfinity or a != int(a):
  1149. raise NotImplementedError
  1150. # Use fast hypergeometric summation if possible
  1151. v = hypsum(func, n, int(a), prec2)
  1152. delta = prec - fastlog(v)
  1153. if fastlog(v) < -10:
  1154. v = hypsum(func, n, int(a), delta)
  1155. return v, None, min(prec, delta), None
  1156. except NotImplementedError:
  1157. # Euler-Maclaurin summation for general series
  1158. eps = Float(2.0)**(-prec)
  1159. for i in range(1, 5):
  1160. m = n = 2**i * prec
  1161. s, err = expr.euler_maclaurin(m=m, n=n, eps=eps,
  1162. eval_integral=False)
  1163. err = err.evalf()
  1164. if err is S.NaN:
  1165. raise NotImplementedError
  1166. if err <= eps:
  1167. break
  1168. err = fastlog(evalf(abs(err), 20, options)[0])
  1169. re, im, re_acc, im_acc = evalf(s, prec2, options)
  1170. if re_acc is None:
  1171. re_acc = -err
  1172. if im_acc is None:
  1173. im_acc = -err
  1174. return re, im, re_acc, im_acc
  1175. #----------------------------------------------------------------------------#
  1176. # #
  1177. # Symbolic interface #
  1178. # #
  1179. #----------------------------------------------------------------------------#
  1180. def evalf_symbol(x: Expr, prec: int, options: OPT_DICT) -> TMP_RES:
  1181. val = options['subs'][x]
  1182. if isinstance(val, mpf):
  1183. if not val:
  1184. return None, None, None, None
  1185. return val._mpf_, None, prec, None
  1186. else:
  1187. if '_cache' not in options:
  1188. options['_cache'] = {}
  1189. cache = options['_cache']
  1190. cached, cached_prec = cache.get(x, (None, MINUS_INF))
  1191. if cached_prec >= prec:
  1192. return cached
  1193. v = evalf(sympify(val), prec, options)
  1194. cache[x] = (v, prec)
  1195. return v
  1196. evalf_table: dict[Type[Expr], Callable[[Expr, int, OPT_DICT], TMP_RES]] = {}
  1197. def _create_evalf_table():
  1198. global evalf_table
  1199. from sympy.concrete.products import Product
  1200. from sympy.concrete.summations import Sum
  1201. from .add import Add
  1202. from .mul import Mul
  1203. from .numbers import Exp1, Float, Half, ImaginaryUnit, Integer, NaN, NegativeOne, One, Pi, Rational, \
  1204. Zero, ComplexInfinity, AlgebraicNumber
  1205. from .power import Pow
  1206. from .symbol import Dummy, Symbol
  1207. from sympy.functions.elementary.complexes import Abs, im, re
  1208. from sympy.functions.elementary.exponential import exp, log
  1209. from sympy.functions.elementary.integers import ceiling, floor
  1210. from sympy.functions.elementary.piecewise import Piecewise
  1211. from sympy.functions.elementary.trigonometric import atan, cos, sin, tan
  1212. from sympy.integrals.integrals import Integral
  1213. evalf_table = {
  1214. Symbol: evalf_symbol,
  1215. Dummy: evalf_symbol,
  1216. Float: evalf_float,
  1217. Rational: evalf_rational,
  1218. Integer: evalf_integer,
  1219. Zero: lambda x, prec, options: (None, None, prec, None),
  1220. One: lambda x, prec, options: (fone, None, prec, None),
  1221. Half: lambda x, prec, options: (fhalf, None, prec, None),
  1222. Pi: lambda x, prec, options: (mpf_pi(prec), None, prec, None),
  1223. Exp1: lambda x, prec, options: (mpf_e(prec), None, prec, None),
  1224. ImaginaryUnit: lambda x, prec, options: (None, fone, None, prec),
  1225. NegativeOne: lambda x, prec, options: (fnone, None, prec, None),
  1226. ComplexInfinity: lambda x, prec, options: S.ComplexInfinity,
  1227. NaN: lambda x, prec, options: (fnan, None, prec, None),
  1228. exp: evalf_exp,
  1229. cos: evalf_trig,
  1230. sin: evalf_trig,
  1231. tan: evalf_trig,
  1232. Add: evalf_add,
  1233. Mul: evalf_mul,
  1234. Pow: evalf_pow,
  1235. log: evalf_log,
  1236. atan: evalf_atan,
  1237. Abs: evalf_abs,
  1238. re: evalf_re,
  1239. im: evalf_im,
  1240. floor: evalf_floor,
  1241. ceiling: evalf_ceiling,
  1242. Integral: evalf_integral,
  1243. Sum: evalf_sum,
  1244. Product: evalf_prod,
  1245. Piecewise: evalf_piecewise,
  1246. AlgebraicNumber: evalf_alg_num,
  1247. }
  1248. def evalf(x: Expr, prec: int, options: OPT_DICT) -> TMP_RES:
  1249. """
  1250. Evaluate the ``Expr`` instance, ``x``
  1251. to a binary precision of ``prec``. This
  1252. function is supposed to be used internally.
  1253. Parameters
  1254. ==========
  1255. x : Expr
  1256. The formula to evaluate to a float.
  1257. prec : int
  1258. The binary precision that the output should have.
  1259. options : dict
  1260. A dictionary with the same entries as
  1261. ``EvalfMixin.evalf`` and in addition,
  1262. ``maxprec`` which is the maximum working precision.
  1263. Returns
  1264. =======
  1265. An optional tuple, ``(re, im, re_acc, im_acc)``
  1266. which are the real, imaginary, real accuracy
  1267. and imaginary accuracy respectively. ``re`` is
  1268. an mpf value tuple and so is ``im``. ``re_acc``
  1269. and ``im_acc`` are ints.
  1270. NB: all these return values can be ``None``.
  1271. If all values are ``None``, then that represents 0.
  1272. Note that 0 is also represented as ``fzero = (0, 0, 0, 0)``.
  1273. """
  1274. from sympy.functions.elementary.complexes import re as re_, im as im_
  1275. try:
  1276. rf = evalf_table[type(x)]
  1277. r = rf(x, prec, options)
  1278. except KeyError:
  1279. # Fall back to ordinary evalf if possible
  1280. if 'subs' in options:
  1281. x = x.subs(evalf_subs(prec, options['subs']))
  1282. xe = x._eval_evalf(prec)
  1283. if xe is None:
  1284. raise NotImplementedError
  1285. as_real_imag = getattr(xe, "as_real_imag", None)
  1286. if as_real_imag is None:
  1287. raise NotImplementedError # e.g. FiniteSet(-1.0, 1.0).evalf()
  1288. re, im = as_real_imag()
  1289. if re.has(re_) or im.has(im_):
  1290. raise NotImplementedError
  1291. if not re:
  1292. re = None
  1293. reprec = None
  1294. elif re.is_number:
  1295. re = re._to_mpmath(prec, allow_ints=False)._mpf_
  1296. reprec = prec
  1297. else:
  1298. raise NotImplementedError
  1299. if not im:
  1300. im = None
  1301. imprec = None
  1302. elif im.is_number:
  1303. im = im._to_mpmath(prec, allow_ints=False)._mpf_
  1304. imprec = prec
  1305. else:
  1306. raise NotImplementedError
  1307. r = re, im, reprec, imprec
  1308. if options.get("verbose"):
  1309. print("### input", x)
  1310. print("### output", to_str(r[0] or fzero, 50) if isinstance(r, tuple) else r)
  1311. print("### raw", r) # r[0], r[2]
  1312. print()
  1313. chop = options.get('chop', False)
  1314. if chop:
  1315. if chop is True:
  1316. chop_prec = prec
  1317. else:
  1318. # convert (approximately) from given tolerance;
  1319. # the formula here will will make 1e-i rounds to 0 for
  1320. # i in the range +/-27 while 2e-i will not be chopped
  1321. chop_prec = int(round(-3.321*math.log10(chop) + 2.5))
  1322. if chop_prec == 3:
  1323. chop_prec -= 1
  1324. r = chop_parts(r, chop_prec)
  1325. if options.get("strict"):
  1326. check_target(x, r, prec)
  1327. return r
  1328. def quad_to_mpmath(q, ctx=None):
  1329. """Turn the quad returned by ``evalf`` into an ``mpf`` or ``mpc``. """
  1330. mpc = make_mpc if ctx is None else ctx.make_mpc
  1331. mpf = make_mpf if ctx is None else ctx.make_mpf
  1332. if q is S.ComplexInfinity:
  1333. raise NotImplementedError
  1334. re, im, _, _ = q
  1335. if im:
  1336. if not re:
  1337. re = fzero
  1338. return mpc((re, im))
  1339. elif re:
  1340. return mpf(re)
  1341. else:
  1342. return mpf(fzero)
  1343. class EvalfMixin:
  1344. """Mixin class adding evalf capability."""
  1345. __slots__: tuple[str, ...] = ()
  1346. def evalf(self, n=15, subs=None, maxn=100, chop=False, strict=False, quad=None, verbose=False):
  1347. """
  1348. Evaluate the given formula to an accuracy of *n* digits.
  1349. Parameters
  1350. ==========
  1351. subs : dict, optional
  1352. Substitute numerical values for symbols, e.g.
  1353. ``subs={x:3, y:1+pi}``. The substitutions must be given as a
  1354. dictionary.
  1355. maxn : int, optional
  1356. Allow a maximum temporary working precision of maxn digits.
  1357. chop : bool or number, optional
  1358. Specifies how to replace tiny real or imaginary parts in
  1359. subresults by exact zeros.
  1360. When ``True`` the chop value defaults to standard precision.
  1361. Otherwise the chop value is used to determine the
  1362. magnitude of "small" for purposes of chopping.
  1363. >>> from sympy import N
  1364. >>> x = 1e-4
  1365. >>> N(x, chop=True)
  1366. 0.000100000000000000
  1367. >>> N(x, chop=1e-5)
  1368. 0.000100000000000000
  1369. >>> N(x, chop=1e-4)
  1370. 0
  1371. strict : bool, optional
  1372. Raise ``PrecisionExhausted`` if any subresult fails to
  1373. evaluate to full accuracy, given the available maxprec.
  1374. quad : str, optional
  1375. Choose algorithm for numerical quadrature. By default,
  1376. tanh-sinh quadrature is used. For oscillatory
  1377. integrals on an infinite interval, try ``quad='osc'``.
  1378. verbose : bool, optional
  1379. Print debug information.
  1380. Notes
  1381. =====
  1382. When Floats are naively substituted into an expression,
  1383. precision errors may adversely affect the result. For example,
  1384. adding 1e16 (a Float) to 1 will truncate to 1e16; if 1e16 is
  1385. then subtracted, the result will be 0.
  1386. That is exactly what happens in the following:
  1387. >>> from sympy.abc import x, y, z
  1388. >>> values = {x: 1e16, y: 1, z: 1e16}
  1389. >>> (x + y - z).subs(values)
  1390. 0
  1391. Using the subs argument for evalf is the accurate way to
  1392. evaluate such an expression:
  1393. >>> (x + y - z).evalf(subs=values)
  1394. 1.00000000000000
  1395. """
  1396. from .numbers import Float, Number
  1397. n = n if n is not None else 15
  1398. if subs and is_sequence(subs):
  1399. raise TypeError('subs must be given as a dictionary')
  1400. # for sake of sage that doesn't like evalf(1)
  1401. if n == 1 and isinstance(self, Number):
  1402. from .expr import _mag
  1403. rv = self.evalf(2, subs, maxn, chop, strict, quad, verbose)
  1404. m = _mag(rv)
  1405. rv = rv.round(1 - m)
  1406. return rv
  1407. if not evalf_table:
  1408. _create_evalf_table()
  1409. prec = dps_to_prec(n)
  1410. options = {'maxprec': max(prec, int(maxn*LG10)), 'chop': chop,
  1411. 'strict': strict, 'verbose': verbose}
  1412. if subs is not None:
  1413. options['subs'] = subs
  1414. if quad is not None:
  1415. options['quad'] = quad
  1416. try:
  1417. result = evalf(self, prec + 4, options)
  1418. except NotImplementedError:
  1419. # Fall back to the ordinary evalf
  1420. if hasattr(self, 'subs') and subs is not None: # issue 20291
  1421. v = self.subs(subs)._eval_evalf(prec)
  1422. else:
  1423. v = self._eval_evalf(prec)
  1424. if v is None:
  1425. return self
  1426. elif not v.is_number:
  1427. return v
  1428. try:
  1429. # If the result is numerical, normalize it
  1430. result = evalf(v, prec, options)
  1431. except NotImplementedError:
  1432. # Probably contains symbols or unknown functions
  1433. return v
  1434. if result is S.ComplexInfinity:
  1435. return result
  1436. re, im, re_acc, im_acc = result
  1437. if re is S.NaN or im is S.NaN:
  1438. return S.NaN
  1439. if re:
  1440. p = max(min(prec, re_acc), 1)
  1441. re = Float._new(re, p)
  1442. else:
  1443. re = S.Zero
  1444. if im:
  1445. p = max(min(prec, im_acc), 1)
  1446. im = Float._new(im, p)
  1447. return re + im*S.ImaginaryUnit
  1448. else:
  1449. return re
  1450. n = evalf
  1451. def _evalf(self, prec: int) -> Expr:
  1452. """Helper for evalf. Does the same thing but takes binary precision"""
  1453. r = self._eval_evalf(prec)
  1454. if r is None:
  1455. r = self # type: ignore
  1456. return r # type: ignore
  1457. def _eval_evalf(self, prec: int) -> Expr | None:
  1458. return None
  1459. def _to_mpmath(self, prec, allow_ints=True):
  1460. # mpmath functions accept ints as input
  1461. errmsg = "cannot convert to mpmath number"
  1462. if allow_ints and self.is_Integer:
  1463. return self.p
  1464. if hasattr(self, '_as_mpf_val'):
  1465. return make_mpf(self._as_mpf_val(prec))
  1466. try:
  1467. result = evalf(self, prec, {})
  1468. return quad_to_mpmath(result)
  1469. except NotImplementedError:
  1470. v = self._eval_evalf(prec)
  1471. if v is None:
  1472. raise ValueError(errmsg)
  1473. if v.is_Float:
  1474. return make_mpf(v._mpf_)
  1475. # Number + Number*I is also fine
  1476. re, im = v.as_real_imag()
  1477. if allow_ints and re.is_Integer:
  1478. re = from_int(re.p)
  1479. elif re.is_Float:
  1480. re = re._mpf_
  1481. else:
  1482. raise ValueError(errmsg)
  1483. if allow_ints and im.is_Integer:
  1484. im = from_int(im.p)
  1485. elif im.is_Float:
  1486. im = im._mpf_
  1487. else:
  1488. raise ValueError(errmsg)
  1489. return make_mpc((re, im))
  1490. def N(x, n=15, **options):
  1491. r"""
  1492. Calls x.evalf(n, \*\*options).
  1493. Explanations
  1494. ============
  1495. Both .n() and N() are equivalent to .evalf(); use the one that you like better.
  1496. See also the docstring of .evalf() for information on the options.
  1497. Examples
  1498. ========
  1499. >>> from sympy import Sum, oo, N
  1500. >>> from sympy.abc import k
  1501. >>> Sum(1/k**k, (k, 1, oo))
  1502. Sum(k**(-k), (k, 1, oo))
  1503. >>> N(_, 4)
  1504. 1.291
  1505. """
  1506. # by using rational=True, any evaluation of a string
  1507. # will be done using exact values for the Floats
  1508. return sympify(x, rational=True).evalf(n, **options)
  1509. def _evalf_with_bounded_error(x: Expr, eps: Expr | None = None,
  1510. m: int = 0,
  1511. options: OPT_DICT | None = None) -> TMP_RES:
  1512. """
  1513. Evaluate *x* to within a bounded absolute error.
  1514. Parameters
  1515. ==========
  1516. x : Expr
  1517. The quantity to be evaluated.
  1518. eps : Expr, None, optional (default=None)
  1519. Positive real upper bound on the acceptable error.
  1520. m : int, optional (default=0)
  1521. If *eps* is None, then use 2**(-m) as the upper bound on the error.
  1522. options: OPT_DICT
  1523. As in the ``evalf`` function.
  1524. Returns
  1525. =======
  1526. A tuple ``(re, im, re_acc, im_acc)``, as returned by ``evalf``.
  1527. See Also
  1528. ========
  1529. evalf
  1530. """
  1531. if eps is not None:
  1532. if not (eps.is_Rational or eps.is_Float) or not eps > 0:
  1533. raise ValueError("eps must be positive")
  1534. r, _, _, _ = evalf(1/eps, 1, {})
  1535. m = fastlog(r)
  1536. c, d, _, _ = evalf(x, 1, {})
  1537. # Note: If x = a + b*I, then |a| <= 2|c| and |b| <= 2|d|, with equality
  1538. # only in the zero case.
  1539. # If a is non-zero, then |c| = 2**nc for some integer nc, and c has
  1540. # bitcount 1. Therefore 2**fastlog(c) = 2**(nc+1) = 2|c| is an upper bound
  1541. # on |a|. Likewise for b and d.
  1542. nr, ni = fastlog(c), fastlog(d)
  1543. n = max(nr, ni) + 1
  1544. # If x is 0, then n is MINUS_INF, and p will be 1. Otherwise,
  1545. # n - 1 bits get us past the integer parts of a and b, and +1 accounts for
  1546. # the factor of <= sqrt(2) that is |x|/max(|a|, |b|).
  1547. p = max(1, m + n + 1)
  1548. options = options or {}
  1549. return evalf(x, p, options)