图片解析应用
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1812 lines
61 KiB

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