m2m模型翻译
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.

4490 lines
133 KiB

6 months ago
  1. import numbers
  2. import decimal
  3. import fractions
  4. import math
  5. import re as regex
  6. import sys
  7. from functools import lru_cache
  8. from typing import Set as tSet, Tuple as tTuple
  9. from .containers import Tuple
  10. from .sympify import (SympifyError, _sympy_converter, sympify, _convert_numpy_types,
  11. _sympify, _is_numpy_instance)
  12. from .singleton import S, Singleton
  13. from .basic import Basic
  14. from .expr import Expr, AtomicExpr
  15. from .evalf import pure_complex
  16. from .cache import cacheit, clear_cache
  17. from .decorators import _sympifyit
  18. from .logic import fuzzy_not
  19. from .kind import NumberKind
  20. from sympy.external.gmpy import SYMPY_INTS, HAS_GMPY, gmpy
  21. from sympy.multipledispatch import dispatch
  22. import mpmath
  23. import mpmath.libmp as mlib
  24. from mpmath.libmp import bitcount, round_nearest as rnd
  25. from mpmath.libmp.backend import MPZ
  26. from mpmath.libmp import mpf_pow, mpf_pi, mpf_e, phi_fixed
  27. from mpmath.ctx_mp import mpnumeric
  28. from mpmath.libmp.libmpf import (
  29. finf as _mpf_inf, fninf as _mpf_ninf,
  30. fnan as _mpf_nan, fzero, _normalize as mpf_normalize,
  31. prec_to_dps, dps_to_prec)
  32. from sympy.utilities.misc import as_int, debug, filldedent
  33. from .parameters import global_parameters
  34. _LOG2 = math.log(2)
  35. def comp(z1, z2, tol=None):
  36. r"""Return a bool indicating whether the error between z1 and z2
  37. is $\le$ ``tol``.
  38. Examples
  39. ========
  40. If ``tol`` is ``None`` then ``True`` will be returned if
  41. :math:`|z1 - z2|\times 10^p \le 5` where $p$ is minimum value of the
  42. decimal precision of each value.
  43. >>> from sympy import comp, pi
  44. >>> pi4 = pi.n(4); pi4
  45. 3.142
  46. >>> comp(_, 3.142)
  47. True
  48. >>> comp(pi4, 3.141)
  49. False
  50. >>> comp(pi4, 3.143)
  51. False
  52. A comparison of strings will be made
  53. if ``z1`` is a Number and ``z2`` is a string or ``tol`` is ''.
  54. >>> comp(pi4, 3.1415)
  55. True
  56. >>> comp(pi4, 3.1415, '')
  57. False
  58. When ``tol`` is provided and $z2$ is non-zero and
  59. :math:`|z1| > 1` the error is normalized by :math:`|z1|`:
  60. >>> abs(pi4 - 3.14)/pi4
  61. 0.000509791731426756
  62. >>> comp(pi4, 3.14, .001) # difference less than 0.1%
  63. True
  64. >>> comp(pi4, 3.14, .0005) # difference less than 0.1%
  65. False
  66. When :math:`|z1| \le 1` the absolute error is used:
  67. >>> 1/pi4
  68. 0.3183
  69. >>> abs(1/pi4 - 0.3183)/(1/pi4)
  70. 3.07371499106316e-5
  71. >>> abs(1/pi4 - 0.3183)
  72. 9.78393554684764e-6
  73. >>> comp(1/pi4, 0.3183, 1e-5)
  74. True
  75. To see if the absolute error between ``z1`` and ``z2`` is less
  76. than or equal to ``tol``, call this as ``comp(z1 - z2, 0, tol)``
  77. or ``comp(z1 - z2, tol=tol)``:
  78. >>> abs(pi4 - 3.14)
  79. 0.00160156249999988
  80. >>> comp(pi4 - 3.14, 0, .002)
  81. True
  82. >>> comp(pi4 - 3.14, 0, .001)
  83. False
  84. """
  85. if isinstance(z2, str):
  86. if not pure_complex(z1, or_real=True):
  87. raise ValueError('when z2 is a str z1 must be a Number')
  88. return str(z1) == z2
  89. if not z1:
  90. z1, z2 = z2, z1
  91. if not z1:
  92. return True
  93. if not tol:
  94. a, b = z1, z2
  95. if tol == '':
  96. return str(a) == str(b)
  97. if tol is None:
  98. a, b = sympify(a), sympify(b)
  99. if not all(i.is_number for i in (a, b)):
  100. raise ValueError('expecting 2 numbers')
  101. fa = a.atoms(Float)
  102. fb = b.atoms(Float)
  103. if not fa and not fb:
  104. # no floats -- compare exactly
  105. return a == b
  106. # get a to be pure_complex
  107. for _ in range(2):
  108. ca = pure_complex(a, or_real=True)
  109. if not ca:
  110. if fa:
  111. a = a.n(prec_to_dps(min([i._prec for i in fa])))
  112. ca = pure_complex(a, or_real=True)
  113. break
  114. else:
  115. fa, fb = fb, fa
  116. a, b = b, a
  117. cb = pure_complex(b)
  118. if not cb and fb:
  119. b = b.n(prec_to_dps(min([i._prec for i in fb])))
  120. cb = pure_complex(b, or_real=True)
  121. if ca and cb and (ca[1] or cb[1]):
  122. return all(comp(i, j) for i, j in zip(ca, cb))
  123. tol = 10**prec_to_dps(min(a._prec, getattr(b, '_prec', a._prec)))
  124. return int(abs(a - b)*tol) <= 5
  125. diff = abs(z1 - z2)
  126. az1 = abs(z1)
  127. if z2 and az1 > 1:
  128. return diff/az1 <= tol
  129. else:
  130. return diff <= tol
  131. def mpf_norm(mpf, prec):
  132. """Return the mpf tuple normalized appropriately for the indicated
  133. precision after doing a check to see if zero should be returned or
  134. not when the mantissa is 0. ``mpf_normlize`` always assumes that this
  135. is zero, but it may not be since the mantissa for mpf's values "+inf",
  136. "-inf" and "nan" have a mantissa of zero, too.
  137. Note: this is not intended to validate a given mpf tuple, so sending
  138. mpf tuples that were not created by mpmath may produce bad results. This
  139. is only a wrapper to ``mpf_normalize`` which provides the check for non-
  140. zero mpfs that have a 0 for the mantissa.
  141. """
  142. sign, man, expt, bc = mpf
  143. if not man:
  144. # hack for mpf_normalize which does not do this;
  145. # it assumes that if man is zero the result is 0
  146. # (see issue 6639)
  147. if not bc:
  148. return fzero
  149. else:
  150. # don't change anything; this should already
  151. # be a well formed mpf tuple
  152. return mpf
  153. # Necessary if mpmath is using the gmpy backend
  154. from mpmath.libmp.backend import MPZ
  155. rv = mpf_normalize(sign, MPZ(man), expt, bc, prec, rnd)
  156. return rv
  157. # TODO: we should use the warnings module
  158. _errdict = {"divide": False}
  159. def seterr(divide=False):
  160. """
  161. Should SymPy raise an exception on 0/0 or return a nan?
  162. divide == True .... raise an exception
  163. divide == False ... return nan
  164. """
  165. if _errdict["divide"] != divide:
  166. clear_cache()
  167. _errdict["divide"] = divide
  168. def _as_integer_ratio(p):
  169. neg_pow, man, expt, _ = getattr(p, '_mpf_', mpmath.mpf(p)._mpf_)
  170. p = [1, -1][neg_pow % 2]*man
  171. if expt < 0:
  172. q = 2**-expt
  173. else:
  174. q = 1
  175. p *= 2**expt
  176. return int(p), int(q)
  177. def _decimal_to_Rational_prec(dec):
  178. """Convert an ordinary decimal instance to a Rational."""
  179. if not dec.is_finite():
  180. raise TypeError("dec must be finite, got %s." % dec)
  181. s, d, e = dec.as_tuple()
  182. prec = len(d)
  183. if e >= 0: # it's an integer
  184. rv = Integer(int(dec))
  185. else:
  186. s = (-1)**s
  187. d = sum([di*10**i for i, di in enumerate(reversed(d))])
  188. rv = Rational(s*d, 10**-e)
  189. return rv, prec
  190. _floatpat = regex.compile(r"[-+]?((\d*\.\d+)|(\d+\.?))")
  191. def _literal_float(f):
  192. """Return True if n starts like a floating point number."""
  193. return bool(_floatpat.match(f))
  194. # (a,b) -> gcd(a,b)
  195. # TODO caching with decorator, but not to degrade performance
  196. @lru_cache(1024)
  197. def igcd(*args):
  198. """Computes nonnegative integer greatest common divisor.
  199. Explanation
  200. ===========
  201. The algorithm is based on the well known Euclid's algorithm [1]_. To
  202. improve speed, ``igcd()`` has its own caching mechanism.
  203. Examples
  204. ========
  205. >>> from sympy import igcd
  206. >>> igcd(2, 4)
  207. 2
  208. >>> igcd(5, 10, 15)
  209. 5
  210. References
  211. ==========
  212. .. [1] https://en.wikipedia.org/wiki/Euclidean_algorithm
  213. """
  214. if len(args) < 2:
  215. raise TypeError(
  216. 'igcd() takes at least 2 arguments (%s given)' % len(args))
  217. args_temp = [abs(as_int(i)) for i in args]
  218. if 1 in args_temp:
  219. return 1
  220. a = args_temp.pop()
  221. if HAS_GMPY: # Using gmpy if present to speed up.
  222. for b in args_temp:
  223. a = gmpy.gcd(a, b) if b else a
  224. return as_int(a)
  225. for b in args_temp:
  226. a = math.gcd(a, b)
  227. return a
  228. igcd2 = math.gcd
  229. def igcd_lehmer(a, b):
  230. r"""Computes greatest common divisor of two integers.
  231. Explanation
  232. ===========
  233. Euclid's algorithm for the computation of the greatest
  234. common divisor ``gcd(a, b)`` of two (positive) integers
  235. $a$ and $b$ is based on the division identity
  236. $$ a = q \times b + r$$,
  237. where the quotient $q$ and the remainder $r$ are integers
  238. and $0 \le r < b$. Then each common divisor of $a$ and $b$
  239. divides $r$, and it follows that ``gcd(a, b) == gcd(b, r)``.
  240. The algorithm works by constructing the sequence
  241. r0, r1, r2, ..., where r0 = a, r1 = b, and each rn
  242. is the remainder from the division of the two preceding
  243. elements.
  244. In Python, ``q = a // b`` and ``r = a % b`` are obtained by the
  245. floor division and the remainder operations, respectively.
  246. These are the most expensive arithmetic operations, especially
  247. for large a and b.
  248. Lehmer's algorithm [1]_ is based on the observation that the quotients
  249. ``qn = r(n-1) // rn`` are in general small integers even
  250. when a and b are very large. Hence the quotients can be
  251. usually determined from a relatively small number of most
  252. significant bits.
  253. The efficiency of the algorithm is further enhanced by not
  254. computing each long remainder in Euclid's sequence. The remainders
  255. are linear combinations of a and b with integer coefficients
  256. derived from the quotients. The coefficients can be computed
  257. as far as the quotients can be determined from the chosen
  258. most significant parts of a and b. Only then a new pair of
  259. consecutive remainders is computed and the algorithm starts
  260. anew with this pair.
  261. References
  262. ==========
  263. .. [1] https://en.wikipedia.org/wiki/Lehmer%27s_GCD_algorithm
  264. """
  265. a, b = abs(as_int(a)), abs(as_int(b))
  266. if a < b:
  267. a, b = b, a
  268. # The algorithm works by using one or two digit division
  269. # whenever possible. The outer loop will replace the
  270. # pair (a, b) with a pair of shorter consecutive elements
  271. # of the Euclidean gcd sequence until a and b
  272. # fit into two Python (long) int digits.
  273. nbits = 2*sys.int_info.bits_per_digit
  274. while a.bit_length() > nbits and b != 0:
  275. # Quotients are mostly small integers that can
  276. # be determined from most significant bits.
  277. n = a.bit_length() - nbits
  278. x, y = int(a >> n), int(b >> n) # most significant bits
  279. # Elements of the Euclidean gcd sequence are linear
  280. # combinations of a and b with integer coefficients.
  281. # Compute the coefficients of consecutive pairs
  282. # a' = A*a + B*b, b' = C*a + D*b
  283. # using small integer arithmetic as far as possible.
  284. A, B, C, D = 1, 0, 0, 1 # initial values
  285. while True:
  286. # The coefficients alternate in sign while looping.
  287. # The inner loop combines two steps to keep track
  288. # of the signs.
  289. # At this point we have
  290. # A > 0, B <= 0, C <= 0, D > 0,
  291. # x' = x + B <= x < x" = x + A,
  292. # y' = y + C <= y < y" = y + D,
  293. # and
  294. # x'*N <= a' < x"*N, y'*N <= b' < y"*N,
  295. # where N = 2**n.
  296. # Now, if y' > 0, and x"//y' and x'//y" agree,
  297. # then their common value is equal to q = a'//b'.
  298. # In addition,
  299. # x'%y" = x' - q*y" < x" - q*y' = x"%y',
  300. # and
  301. # (x'%y")*N < a'%b' < (x"%y')*N.
  302. # On the other hand, we also have x//y == q,
  303. # and therefore
  304. # x'%y" = x + B - q*(y + D) = x%y + B',
  305. # x"%y' = x + A - q*(y + C) = x%y + A',
  306. # where
  307. # B' = B - q*D < 0, A' = A - q*C > 0.
  308. if y + C <= 0:
  309. break
  310. q = (x + A) // (y + C)
  311. # Now x'//y" <= q, and equality holds if
  312. # x' - q*y" = (x - q*y) + (B - q*D) >= 0.
  313. # This is a minor optimization to avoid division.
  314. x_qy, B_qD = x - q*y, B - q*D
  315. if x_qy + B_qD < 0:
  316. break
  317. # Next step in the Euclidean sequence.
  318. x, y = y, x_qy
  319. A, B, C, D = C, D, A - q*C, B_qD
  320. # At this point the signs of the coefficients
  321. # change and their roles are interchanged.
  322. # A <= 0, B > 0, C > 0, D < 0,
  323. # x' = x + A <= x < x" = x + B,
  324. # y' = y + D < y < y" = y + C.
  325. if y + D <= 0:
  326. break
  327. q = (x + B) // (y + D)
  328. x_qy, A_qC = x - q*y, A - q*C
  329. if x_qy + A_qC < 0:
  330. break
  331. x, y = y, x_qy
  332. A, B, C, D = C, D, A_qC, B - q*D
  333. # Now the conditions on top of the loop
  334. # are again satisfied.
  335. # A > 0, B < 0, C < 0, D > 0.
  336. if B == 0:
  337. # This can only happen when y == 0 in the beginning
  338. # and the inner loop does nothing.
  339. # Long division is forced.
  340. a, b = b, a % b
  341. continue
  342. # Compute new long arguments using the coefficients.
  343. a, b = A*a + B*b, C*a + D*b
  344. # Small divisors. Finish with the standard algorithm.
  345. while b:
  346. a, b = b, a % b
  347. return a
  348. def ilcm(*args):
  349. """Computes integer least common multiple.
  350. Examples
  351. ========
  352. >>> from sympy import ilcm
  353. >>> ilcm(5, 10)
  354. 10
  355. >>> ilcm(7, 3)
  356. 21
  357. >>> ilcm(5, 10, 15)
  358. 30
  359. """
  360. if len(args) < 2:
  361. raise TypeError(
  362. 'ilcm() takes at least 2 arguments (%s given)' % len(args))
  363. if 0 in args:
  364. return 0
  365. a = args[0]
  366. for b in args[1:]:
  367. a = a // igcd(a, b) * b # since gcd(a,b) | a
  368. return a
  369. def igcdex(a, b):
  370. """Returns x, y, g such that g = x*a + y*b = gcd(a, b).
  371. Examples
  372. ========
  373. >>> from sympy.core.numbers import igcdex
  374. >>> igcdex(2, 3)
  375. (-1, 1, 1)
  376. >>> igcdex(10, 12)
  377. (-1, 1, 2)
  378. >>> x, y, g = igcdex(100, 2004)
  379. >>> x, y, g
  380. (-20, 1, 4)
  381. >>> x*100 + y*2004
  382. 4
  383. """
  384. if (not a) and (not b):
  385. return (0, 1, 0)
  386. if not a:
  387. return (0, b//abs(b), abs(b))
  388. if not b:
  389. return (a//abs(a), 0, abs(a))
  390. if a < 0:
  391. a, x_sign = -a, -1
  392. else:
  393. x_sign = 1
  394. if b < 0:
  395. b, y_sign = -b, -1
  396. else:
  397. y_sign = 1
  398. x, y, r, s = 1, 0, 0, 1
  399. while b:
  400. (c, q) = (a % b, a // b)
  401. (a, b, r, s, x, y) = (b, c, x - q*r, y - q*s, r, s)
  402. return (x*x_sign, y*y_sign, a)
  403. def mod_inverse(a, m):
  404. """
  405. Return the number c such that, (a * c) = 1 (mod m)
  406. where c has the same sign as m. If no such value exists,
  407. a ValueError is raised.
  408. Examples
  409. ========
  410. >>> from sympy import mod_inverse, S
  411. Suppose we wish to find multiplicative inverse x of
  412. 3 modulo 11. This is the same as finding x such
  413. that 3 * x = 1 (mod 11). One value of x that satisfies
  414. this congruence is 4. Because 3 * 4 = 12 and 12 = 1 (mod 11).
  415. This is the value returned by mod_inverse:
  416. >>> mod_inverse(3, 11)
  417. 4
  418. >>> mod_inverse(-3, 11)
  419. 7
  420. When there is a common factor between the numerators of
  421. ``a`` and ``m`` the inverse does not exist:
  422. >>> mod_inverse(2, 4)
  423. Traceback (most recent call last):
  424. ...
  425. ValueError: inverse of 2 mod 4 does not exist
  426. >>> mod_inverse(S(2)/7, S(5)/2)
  427. 7/2
  428. References
  429. ==========
  430. .. [1] https://en.wikipedia.org/wiki/Modular_multiplicative_inverse
  431. .. [2] https://en.wikipedia.org/wiki/Extended_Euclidean_algorithm
  432. """
  433. c = None
  434. try:
  435. a, m = as_int(a), as_int(m)
  436. if m != 1 and m != -1:
  437. x, _, g = igcdex(a, m)
  438. if g == 1:
  439. c = x % m
  440. except ValueError:
  441. a, m = sympify(a), sympify(m)
  442. if not (a.is_number and m.is_number):
  443. raise TypeError(filldedent('''
  444. Expected numbers for arguments; symbolic `mod_inverse`
  445. is not implemented
  446. but symbolic expressions can be handled with the
  447. similar function,
  448. sympy.polys.polytools.invert'''))
  449. big = (m > 1)
  450. if big not in (S.true, S.false):
  451. raise ValueError('m > 1 did not evaluate; try to simplify %s' % m)
  452. elif big:
  453. c = 1/a
  454. if c is None:
  455. raise ValueError('inverse of %s (mod %s) does not exist' % (a, m))
  456. return c
  457. class Number(AtomicExpr):
  458. """Represents atomic numbers in SymPy.
  459. Explanation
  460. ===========
  461. Floating point numbers are represented by the Float class.
  462. Rational numbers (of any size) are represented by the Rational class.
  463. Integer numbers (of any size) are represented by the Integer class.
  464. Float and Rational are subclasses of Number; Integer is a subclass
  465. of Rational.
  466. For example, ``2/3`` is represented as ``Rational(2, 3)`` which is
  467. a different object from the floating point number obtained with
  468. Python division ``2/3``. Even for numbers that are exactly
  469. represented in binary, there is a difference between how two forms,
  470. such as ``Rational(1, 2)`` and ``Float(0.5)``, are used in SymPy.
  471. The rational form is to be preferred in symbolic computations.
  472. Other kinds of numbers, such as algebraic numbers ``sqrt(2)`` or
  473. complex numbers ``3 + 4*I``, are not instances of Number class as
  474. they are not atomic.
  475. See Also
  476. ========
  477. Float, Integer, Rational
  478. """
  479. is_commutative = True
  480. is_number = True
  481. is_Number = True
  482. __slots__ = ()
  483. # Used to make max(x._prec, y._prec) return x._prec when only x is a float
  484. _prec = -1
  485. kind = NumberKind
  486. def __new__(cls, *obj):
  487. if len(obj) == 1:
  488. obj = obj[0]
  489. if isinstance(obj, Number):
  490. return obj
  491. if isinstance(obj, SYMPY_INTS):
  492. return Integer(obj)
  493. if isinstance(obj, tuple) and len(obj) == 2:
  494. return Rational(*obj)
  495. if isinstance(obj, (float, mpmath.mpf, decimal.Decimal)):
  496. return Float(obj)
  497. if isinstance(obj, str):
  498. _obj = obj.lower() # float('INF') == float('inf')
  499. if _obj == 'nan':
  500. return S.NaN
  501. elif _obj == 'inf':
  502. return S.Infinity
  503. elif _obj == '+inf':
  504. return S.Infinity
  505. elif _obj == '-inf':
  506. return S.NegativeInfinity
  507. val = sympify(obj)
  508. if isinstance(val, Number):
  509. return val
  510. else:
  511. raise ValueError('String "%s" does not denote a Number' % obj)
  512. msg = "expected str|int|long|float|Decimal|Number object but got %r"
  513. raise TypeError(msg % type(obj).__name__)
  514. def could_extract_minus_sign(self):
  515. return bool(self.is_extended_negative)
  516. def invert(self, other, *gens, **args):
  517. from sympy.polys.polytools import invert
  518. if getattr(other, 'is_number', True):
  519. return mod_inverse(self, other)
  520. return invert(self, other, *gens, **args)
  521. def __divmod__(self, other):
  522. from sympy.functions.elementary.complexes import sign
  523. try:
  524. other = Number(other)
  525. if self.is_infinite or S.NaN in (self, other):
  526. return (S.NaN, S.NaN)
  527. except TypeError:
  528. return NotImplemented
  529. if not other:
  530. raise ZeroDivisionError('modulo by zero')
  531. if self.is_Integer and other.is_Integer:
  532. return Tuple(*divmod(self.p, other.p))
  533. elif isinstance(other, Float):
  534. rat = self/Rational(other)
  535. else:
  536. rat = self/other
  537. if other.is_finite:
  538. w = int(rat) if rat >= 0 else int(rat) - 1
  539. r = self - other*w
  540. else:
  541. w = 0 if not self or (sign(self) == sign(other)) else -1
  542. r = other if w else self
  543. return Tuple(w, r)
  544. def __rdivmod__(self, other):
  545. try:
  546. other = Number(other)
  547. except TypeError:
  548. return NotImplemented
  549. return divmod(other, self)
  550. def _as_mpf_val(self, prec):
  551. """Evaluation of mpf tuple accurate to at least prec bits."""
  552. raise NotImplementedError('%s needs ._as_mpf_val() method' %
  553. (self.__class__.__name__))
  554. def _eval_evalf(self, prec):
  555. return Float._new(self._as_mpf_val(prec), prec)
  556. def _as_mpf_op(self, prec):
  557. prec = max(prec, self._prec)
  558. return self._as_mpf_val(prec), prec
  559. def __float__(self):
  560. return mlib.to_float(self._as_mpf_val(53))
  561. def floor(self):
  562. raise NotImplementedError('%s needs .floor() method' %
  563. (self.__class__.__name__))
  564. def ceiling(self):
  565. raise NotImplementedError('%s needs .ceiling() method' %
  566. (self.__class__.__name__))
  567. def __floor__(self):
  568. return self.floor()
  569. def __ceil__(self):
  570. return self.ceiling()
  571. def _eval_conjugate(self):
  572. return self
  573. def _eval_order(self, *symbols):
  574. from sympy.series.order import Order
  575. # Order(5, x, y) -> Order(1,x,y)
  576. return Order(S.One, *symbols)
  577. def _eval_subs(self, old, new):
  578. if old == -self:
  579. return -new
  580. return self # there is no other possibility
  581. def _eval_is_finite(self):
  582. return True
  583. @classmethod
  584. def class_key(cls):
  585. return 1, 0, 'Number'
  586. @cacheit
  587. def sort_key(self, order=None):
  588. return self.class_key(), (0, ()), (), self
  589. @_sympifyit('other', NotImplemented)
  590. def __add__(self, other):
  591. if isinstance(other, Number) and global_parameters.evaluate:
  592. if other is S.NaN:
  593. return S.NaN
  594. elif other is S.Infinity:
  595. return S.Infinity
  596. elif other is S.NegativeInfinity:
  597. return S.NegativeInfinity
  598. return AtomicExpr.__add__(self, other)
  599. @_sympifyit('other', NotImplemented)
  600. def __sub__(self, other):
  601. if isinstance(other, Number) and global_parameters.evaluate:
  602. if other is S.NaN:
  603. return S.NaN
  604. elif other is S.Infinity:
  605. return S.NegativeInfinity
  606. elif other is S.NegativeInfinity:
  607. return S.Infinity
  608. return AtomicExpr.__sub__(self, other)
  609. @_sympifyit('other', NotImplemented)
  610. def __mul__(self, other):
  611. if isinstance(other, Number) and global_parameters.evaluate:
  612. if other is S.NaN:
  613. return S.NaN
  614. elif other is S.Infinity:
  615. if self.is_zero:
  616. return S.NaN
  617. elif self.is_positive:
  618. return S.Infinity
  619. else:
  620. return S.NegativeInfinity
  621. elif other is S.NegativeInfinity:
  622. if self.is_zero:
  623. return S.NaN
  624. elif self.is_positive:
  625. return S.NegativeInfinity
  626. else:
  627. return S.Infinity
  628. elif isinstance(other, Tuple):
  629. return NotImplemented
  630. return AtomicExpr.__mul__(self, other)
  631. @_sympifyit('other', NotImplemented)
  632. def __truediv__(self, other):
  633. if isinstance(other, Number) and global_parameters.evaluate:
  634. if other is S.NaN:
  635. return S.NaN
  636. elif other in (S.Infinity, S.NegativeInfinity):
  637. return S.Zero
  638. return AtomicExpr.__truediv__(self, other)
  639. def __eq__(self, other):
  640. raise NotImplementedError('%s needs .__eq__() method' %
  641. (self.__class__.__name__))
  642. def __ne__(self, other):
  643. raise NotImplementedError('%s needs .__ne__() method' %
  644. (self.__class__.__name__))
  645. def __lt__(self, other):
  646. try:
  647. other = _sympify(other)
  648. except SympifyError:
  649. raise TypeError("Invalid comparison %s < %s" % (self, other))
  650. raise NotImplementedError('%s needs .__lt__() method' %
  651. (self.__class__.__name__))
  652. def __le__(self, other):
  653. try:
  654. other = _sympify(other)
  655. except SympifyError:
  656. raise TypeError("Invalid comparison %s <= %s" % (self, other))
  657. raise NotImplementedError('%s needs .__le__() method' %
  658. (self.__class__.__name__))
  659. def __gt__(self, other):
  660. try:
  661. other = _sympify(other)
  662. except SympifyError:
  663. raise TypeError("Invalid comparison %s > %s" % (self, other))
  664. return _sympify(other).__lt__(self)
  665. def __ge__(self, other):
  666. try:
  667. other = _sympify(other)
  668. except SympifyError:
  669. raise TypeError("Invalid comparison %s >= %s" % (self, other))
  670. return _sympify(other).__le__(self)
  671. def __hash__(self):
  672. return super().__hash__()
  673. def is_constant(self, *wrt, **flags):
  674. return True
  675. def as_coeff_mul(self, *deps, rational=True, **kwargs):
  676. # a -> c*t
  677. if self.is_Rational or not rational:
  678. return self, tuple()
  679. elif self.is_negative:
  680. return S.NegativeOne, (-self,)
  681. return S.One, (self,)
  682. def as_coeff_add(self, *deps):
  683. # a -> c + t
  684. if self.is_Rational:
  685. return self, tuple()
  686. return S.Zero, (self,)
  687. def as_coeff_Mul(self, rational=False):
  688. """Efficiently extract the coefficient of a product. """
  689. if rational and not self.is_Rational:
  690. return S.One, self
  691. return (self, S.One) if self else (S.One, self)
  692. def as_coeff_Add(self, rational=False):
  693. """Efficiently extract the coefficient of a summation. """
  694. if not rational:
  695. return self, S.Zero
  696. return S.Zero, self
  697. def gcd(self, other):
  698. """Compute GCD of `self` and `other`. """
  699. from sympy.polys.polytools import gcd
  700. return gcd(self, other)
  701. def lcm(self, other):
  702. """Compute LCM of `self` and `other`. """
  703. from sympy.polys.polytools import lcm
  704. return lcm(self, other)
  705. def cofactors(self, other):
  706. """Compute GCD and cofactors of `self` and `other`. """
  707. from sympy.polys.polytools import cofactors
  708. return cofactors(self, other)
  709. class Float(Number):
  710. """Represent a floating-point number of arbitrary precision.
  711. Examples
  712. ========
  713. >>> from sympy import Float
  714. >>> Float(3.5)
  715. 3.50000000000000
  716. >>> Float(3)
  717. 3.00000000000000
  718. Creating Floats from strings (and Python ``int`` and ``long``
  719. types) will give a minimum precision of 15 digits, but the
  720. precision will automatically increase to capture all digits
  721. entered.
  722. >>> Float(1)
  723. 1.00000000000000
  724. >>> Float(10**20)
  725. 100000000000000000000.
  726. >>> Float('1e20')
  727. 100000000000000000000.
  728. However, *floating-point* numbers (Python ``float`` types) retain
  729. only 15 digits of precision:
  730. >>> Float(1e20)
  731. 1.00000000000000e+20
  732. >>> Float(1.23456789123456789)
  733. 1.23456789123457
  734. It may be preferable to enter high-precision decimal numbers
  735. as strings:
  736. >>> Float('1.23456789123456789')
  737. 1.23456789123456789
  738. The desired number of digits can also be specified:
  739. >>> Float('1e-3', 3)
  740. 0.00100
  741. >>> Float(100, 4)
  742. 100.0
  743. Float can automatically count significant figures if a null string
  744. is sent for the precision; spaces or underscores are also allowed. (Auto-
  745. counting is only allowed for strings, ints and longs).
  746. >>> Float('123 456 789.123_456', '')
  747. 123456789.123456
  748. >>> Float('12e-3', '')
  749. 0.012
  750. >>> Float(3, '')
  751. 3.
  752. If a number is written in scientific notation, only the digits before the
  753. exponent are considered significant if a decimal appears, otherwise the
  754. "e" signifies only how to move the decimal:
  755. >>> Float('60.e2', '') # 2 digits significant
  756. 6.0e+3
  757. >>> Float('60e2', '') # 4 digits significant
  758. 6000.
  759. >>> Float('600e-2', '') # 3 digits significant
  760. 6.00
  761. Notes
  762. =====
  763. Floats are inexact by their nature unless their value is a binary-exact
  764. value.
  765. >>> approx, exact = Float(.1, 1), Float(.125, 1)
  766. For calculation purposes, evalf needs to be able to change the precision
  767. but this will not increase the accuracy of the inexact value. The
  768. following is the most accurate 5-digit approximation of a value of 0.1
  769. that had only 1 digit of precision:
  770. >>> approx.evalf(5)
  771. 0.099609
  772. By contrast, 0.125 is exact in binary (as it is in base 10) and so it
  773. can be passed to Float or evalf to obtain an arbitrary precision with
  774. matching accuracy:
  775. >>> Float(exact, 5)
  776. 0.12500
  777. >>> exact.evalf(20)
  778. 0.12500000000000000000
  779. Trying to make a high-precision Float from a float is not disallowed,
  780. but one must keep in mind that the *underlying float* (not the apparent
  781. decimal value) is being obtained with high precision. For example, 0.3
  782. does not have a finite binary representation. The closest rational is
  783. the fraction 5404319552844595/2**54. So if you try to obtain a Float of
  784. 0.3 to 20 digits of precision you will not see the same thing as 0.3
  785. followed by 19 zeros:
  786. >>> Float(0.3, 20)
  787. 0.29999999999999998890
  788. If you want a 20-digit value of the decimal 0.3 (not the floating point
  789. approximation of 0.3) you should send the 0.3 as a string. The underlying
  790. representation is still binary but a higher precision than Python's float
  791. is used:
  792. >>> Float('0.3', 20)
  793. 0.30000000000000000000
  794. Although you can increase the precision of an existing Float using Float
  795. it will not increase the accuracy -- the underlying value is not changed:
  796. >>> def show(f): # binary rep of Float
  797. ... from sympy import Mul, Pow
  798. ... s, m, e, b = f._mpf_
  799. ... v = Mul(int(m), Pow(2, int(e), evaluate=False), evaluate=False)
  800. ... print('%s at prec=%s' % (v, f._prec))
  801. ...
  802. >>> t = Float('0.3', 3)
  803. >>> show(t)
  804. 4915/2**14 at prec=13
  805. >>> show(Float(t, 20)) # higher prec, not higher accuracy
  806. 4915/2**14 at prec=70
  807. >>> show(Float(t, 2)) # lower prec
  808. 307/2**10 at prec=10
  809. The same thing happens when evalf is used on a Float:
  810. >>> show(t.evalf(20))
  811. 4915/2**14 at prec=70
  812. >>> show(t.evalf(2))
  813. 307/2**10 at prec=10
  814. Finally, Floats can be instantiated with an mpf tuple (n, c, p) to
  815. produce the number (-1)**n*c*2**p:
  816. >>> n, c, p = 1, 5, 0
  817. >>> (-1)**n*c*2**p
  818. -5
  819. >>> Float((1, 5, 0))
  820. -5.00000000000000
  821. An actual mpf tuple also contains the number of bits in c as the last
  822. element of the tuple:
  823. >>> _._mpf_
  824. (1, 5, 0, 3)
  825. This is not needed for instantiation and is not the same thing as the
  826. precision. The mpf tuple and the precision are two separate quantities
  827. that Float tracks.
  828. In SymPy, a Float is a number that can be computed with arbitrary
  829. precision. Although floating point 'inf' and 'nan' are not such
  830. numbers, Float can create these numbers:
  831. >>> Float('-inf')
  832. -oo
  833. >>> _.is_Float
  834. False
  835. """
  836. __slots__ = ('_mpf_', '_prec')
  837. _mpf_: tTuple[int, int, int, int]
  838. # A Float represents many real numbers,
  839. # both rational and irrational.
  840. is_rational = None
  841. is_irrational = None
  842. is_number = True
  843. is_real = True
  844. is_extended_real = True
  845. is_Float = True
  846. def __new__(cls, num, dps=None, precision=None):
  847. if dps is not None and precision is not None:
  848. raise ValueError('Both decimal and binary precision supplied. '
  849. 'Supply only one. ')
  850. if isinstance(num, str):
  851. # Float accepts spaces as digit separators
  852. num = num.replace(' ', '').lower()
  853. if num.startswith('.') and len(num) > 1:
  854. num = '0' + num
  855. elif num.startswith('-.') and len(num) > 2:
  856. num = '-0.' + num[2:]
  857. elif num in ('inf', '+inf'):
  858. return S.Infinity
  859. elif num == '-inf':
  860. return S.NegativeInfinity
  861. elif isinstance(num, float) and num == 0:
  862. num = '0'
  863. elif isinstance(num, float) and num == float('inf'):
  864. return S.Infinity
  865. elif isinstance(num, float) and num == float('-inf'):
  866. return S.NegativeInfinity
  867. elif isinstance(num, float) and math.isnan(num):
  868. return S.NaN
  869. elif isinstance(num, (SYMPY_INTS, Integer)):
  870. num = str(num)
  871. elif num is S.Infinity:
  872. return num
  873. elif num is S.NegativeInfinity:
  874. return num
  875. elif num is S.NaN:
  876. return num
  877. elif _is_numpy_instance(num): # support for numpy datatypes
  878. num = _convert_numpy_types(num)
  879. elif isinstance(num, mpmath.mpf):
  880. if precision is None:
  881. if dps is None:
  882. precision = num.context.prec
  883. num = num._mpf_
  884. if dps is None and precision is None:
  885. dps = 15
  886. if isinstance(num, Float):
  887. return num
  888. if isinstance(num, str) and _literal_float(num):
  889. try:
  890. Num = decimal.Decimal(num)
  891. except decimal.InvalidOperation:
  892. pass
  893. else:
  894. isint = '.' not in num
  895. num, dps = _decimal_to_Rational_prec(Num)
  896. if num.is_Integer and isint:
  897. dps = max(dps, len(str(num).lstrip('-')))
  898. dps = max(15, dps)
  899. precision = dps_to_prec(dps)
  900. elif precision == '' and dps is None or precision is None and dps == '':
  901. if not isinstance(num, str):
  902. raise ValueError('The null string can only be used when '
  903. 'the number to Float is passed as a string or an integer.')
  904. ok = None
  905. if _literal_float(num):
  906. try:
  907. Num = decimal.Decimal(num)
  908. except decimal.InvalidOperation:
  909. pass
  910. else:
  911. isint = '.' not in num
  912. num, dps = _decimal_to_Rational_prec(Num)
  913. if num.is_Integer and isint:
  914. dps = max(dps, len(str(num).lstrip('-')))
  915. precision = dps_to_prec(dps)
  916. ok = True
  917. if ok is None:
  918. raise ValueError('string-float not recognized: %s' % num)
  919. # decimal precision(dps) is set and maybe binary precision(precision)
  920. # as well.From here on binary precision is used to compute the Float.
  921. # Hence, if supplied use binary precision else translate from decimal
  922. # precision.
  923. if precision is None or precision == '':
  924. precision = dps_to_prec(dps)
  925. precision = int(precision)
  926. if isinstance(num, float):
  927. _mpf_ = mlib.from_float(num, precision, rnd)
  928. elif isinstance(num, str):
  929. _mpf_ = mlib.from_str(num, precision, rnd)
  930. elif isinstance(num, decimal.Decimal):
  931. if num.is_finite():
  932. _mpf_ = mlib.from_str(str(num), precision, rnd)
  933. elif num.is_nan():
  934. return S.NaN
  935. elif num.is_infinite():
  936. if num > 0:
  937. return S.Infinity
  938. return S.NegativeInfinity
  939. else:
  940. raise ValueError("unexpected decimal value %s" % str(num))
  941. elif isinstance(num, tuple) and len(num) in (3, 4):
  942. if isinstance(num[1], str):
  943. # it's a hexadecimal (coming from a pickled object)
  944. num = list(num)
  945. # If we're loading an object pickled in Python 2 into
  946. # Python 3, we may need to strip a tailing 'L' because
  947. # of a shim for int on Python 3, see issue #13470.
  948. if num[1].endswith('L'):
  949. num[1] = num[1][:-1]
  950. # Strip leading '0x' - gmpy2 only documents such inputs
  951. # with base prefix as valid when the 2nd argument (base) is 0.
  952. # When mpmath uses Sage as the backend, however, it
  953. # ends up including '0x' when preparing the picklable tuple.
  954. # See issue #19690.
  955. if num[1].startswith('0x'):
  956. num[1] = num[1][2:]
  957. # Now we can assume that it is in standard form
  958. num[1] = MPZ(num[1], 16)
  959. _mpf_ = tuple(num)
  960. else:
  961. if len(num) == 4:
  962. # handle normalization hack
  963. return Float._new(num, precision)
  964. else:
  965. if not all((
  966. num[0] in (0, 1),
  967. num[1] >= 0,
  968. all(type(i) in (int, int) for i in num)
  969. )):
  970. raise ValueError('malformed mpf: %s' % (num,))
  971. # don't compute number or else it may
  972. # over/underflow
  973. return Float._new(
  974. (num[0], num[1], num[2], bitcount(num[1])),
  975. precision)
  976. else:
  977. try:
  978. _mpf_ = num._as_mpf_val(precision)
  979. except (NotImplementedError, AttributeError):
  980. _mpf_ = mpmath.mpf(num, prec=precision)._mpf_
  981. return cls._new(_mpf_, precision, zero=False)
  982. @classmethod
  983. def _new(cls, _mpf_, _prec, zero=True):
  984. # special cases
  985. if zero and _mpf_ == fzero:
  986. return S.Zero # Float(0) -> 0.0; Float._new((0,0,0,0)) -> 0
  987. elif _mpf_ == _mpf_nan:
  988. return S.NaN
  989. elif _mpf_ == _mpf_inf:
  990. return S.Infinity
  991. elif _mpf_ == _mpf_ninf:
  992. return S.NegativeInfinity
  993. obj = Expr.__new__(cls)
  994. obj._mpf_ = mpf_norm(_mpf_, _prec)
  995. obj._prec = _prec
  996. return obj
  997. # mpz can't be pickled
  998. def __getnewargs_ex__(self):
  999. return ((mlib.to_pickable(self._mpf_),), {'precision': self._prec})
  1000. def _hashable_content(self):
  1001. return (self._mpf_, self._prec)
  1002. def floor(self):
  1003. return Integer(int(mlib.to_int(
  1004. mlib.mpf_floor(self._mpf_, self._prec))))
  1005. def ceiling(self):
  1006. return Integer(int(mlib.to_int(
  1007. mlib.mpf_ceil(self._mpf_, self._prec))))
  1008. def __floor__(self):
  1009. return self.floor()
  1010. def __ceil__(self):
  1011. return self.ceiling()
  1012. @property
  1013. def num(self):
  1014. return mpmath.mpf(self._mpf_)
  1015. def _as_mpf_val(self, prec):
  1016. rv = mpf_norm(self._mpf_, prec)
  1017. if rv != self._mpf_ and self._prec == prec:
  1018. debug(self._mpf_, rv)
  1019. return rv
  1020. def _as_mpf_op(self, prec):
  1021. return self._mpf_, max(prec, self._prec)
  1022. def _eval_is_finite(self):
  1023. if self._mpf_ in (_mpf_inf, _mpf_ninf):
  1024. return False
  1025. return True
  1026. def _eval_is_infinite(self):
  1027. if self._mpf_ in (_mpf_inf, _mpf_ninf):
  1028. return True
  1029. return False
  1030. def _eval_is_integer(self):
  1031. return self._mpf_ == fzero
  1032. def _eval_is_negative(self):
  1033. if self._mpf_ in (_mpf_ninf, _mpf_inf):
  1034. return False
  1035. return self.num < 0
  1036. def _eval_is_positive(self):
  1037. if self._mpf_ in (_mpf_ninf, _mpf_inf):
  1038. return False
  1039. return self.num > 0
  1040. def _eval_is_extended_negative(self):
  1041. if self._mpf_ == _mpf_ninf:
  1042. return True
  1043. if self._mpf_ == _mpf_inf:
  1044. return False
  1045. return self.num < 0
  1046. def _eval_is_extended_positive(self):
  1047. if self._mpf_ == _mpf_inf:
  1048. return True
  1049. if self._mpf_ == _mpf_ninf:
  1050. return False
  1051. return self.num > 0
  1052. def _eval_is_zero(self):
  1053. return self._mpf_ == fzero
  1054. def __bool__(self):
  1055. return self._mpf_ != fzero
  1056. def __neg__(self):
  1057. if not self:
  1058. return self
  1059. return Float._new(mlib.mpf_neg(self._mpf_), self._prec)
  1060. @_sympifyit('other', NotImplemented)
  1061. def __add__(self, other):
  1062. if isinstance(other, Number) and global_parameters.evaluate:
  1063. rhs, prec = other._as_mpf_op(self._prec)
  1064. return Float._new(mlib.mpf_add(self._mpf_, rhs, prec, rnd), prec)
  1065. return Number.__add__(self, other)
  1066. @_sympifyit('other', NotImplemented)
  1067. def __sub__(self, other):
  1068. if isinstance(other, Number) and global_parameters.evaluate:
  1069. rhs, prec = other._as_mpf_op(self._prec)
  1070. return Float._new(mlib.mpf_sub(self._mpf_, rhs, prec, rnd), prec)
  1071. return Number.__sub__(self, other)
  1072. @_sympifyit('other', NotImplemented)
  1073. def __mul__(self, other):
  1074. if isinstance(other, Number) and global_parameters.evaluate:
  1075. rhs, prec = other._as_mpf_op(self._prec)
  1076. return Float._new(mlib.mpf_mul(self._mpf_, rhs, prec, rnd), prec)
  1077. return Number.__mul__(self, other)
  1078. @_sympifyit('other', NotImplemented)
  1079. def __truediv__(self, other):
  1080. if isinstance(other, Number) and other != 0 and global_parameters.evaluate:
  1081. rhs, prec = other._as_mpf_op(self._prec)
  1082. return Float._new(mlib.mpf_div(self._mpf_, rhs, prec, rnd), prec)
  1083. return Number.__truediv__(self, other)
  1084. @_sympifyit('other', NotImplemented)
  1085. def __mod__(self, other):
  1086. if isinstance(other, Rational) and other.q != 1 and global_parameters.evaluate:
  1087. # calculate mod with Rationals, *then* round the result
  1088. return Float(Rational.__mod__(Rational(self), other),
  1089. precision=self._prec)
  1090. if isinstance(other, Float) and global_parameters.evaluate:
  1091. r = self/other
  1092. if r == int(r):
  1093. return Float(0, precision=max(self._prec, other._prec))
  1094. if isinstance(other, Number) and global_parameters.evaluate:
  1095. rhs, prec = other._as_mpf_op(self._prec)
  1096. return Float._new(mlib.mpf_mod(self._mpf_, rhs, prec, rnd), prec)
  1097. return Number.__mod__(self, other)
  1098. @_sympifyit('other', NotImplemented)
  1099. def __rmod__(self, other):
  1100. if isinstance(other, Float) and global_parameters.evaluate:
  1101. return other.__mod__(self)
  1102. if isinstance(other, Number) and global_parameters.evaluate:
  1103. rhs, prec = other._as_mpf_op(self._prec)
  1104. return Float._new(mlib.mpf_mod(rhs, self._mpf_, prec, rnd), prec)
  1105. return Number.__rmod__(self, other)
  1106. def _eval_power(self, expt):
  1107. """
  1108. expt is symbolic object but not equal to 0, 1
  1109. (-p)**r -> exp(r*log(-p)) -> exp(r*(log(p) + I*Pi)) ->
  1110. -> p**r*(sin(Pi*r) + cos(Pi*r)*I)
  1111. """
  1112. if self == 0:
  1113. if expt.is_extended_positive:
  1114. return self
  1115. if expt.is_extended_negative:
  1116. return S.ComplexInfinity
  1117. if isinstance(expt, Number):
  1118. if isinstance(expt, Integer):
  1119. prec = self._prec
  1120. return Float._new(
  1121. mlib.mpf_pow_int(self._mpf_, expt.p, prec, rnd), prec)
  1122. elif isinstance(expt, Rational) and \
  1123. expt.p == 1 and expt.q % 2 and self.is_negative:
  1124. return Pow(S.NegativeOne, expt, evaluate=False)*(
  1125. -self)._eval_power(expt)
  1126. expt, prec = expt._as_mpf_op(self._prec)
  1127. mpfself = self._mpf_
  1128. try:
  1129. y = mpf_pow(mpfself, expt, prec, rnd)
  1130. return Float._new(y, prec)
  1131. except mlib.ComplexResult:
  1132. re, im = mlib.mpc_pow(
  1133. (mpfself, fzero), (expt, fzero), prec, rnd)
  1134. return Float._new(re, prec) + \
  1135. Float._new(im, prec)*S.ImaginaryUnit
  1136. def __abs__(self):
  1137. return Float._new(mlib.mpf_abs(self._mpf_), self._prec)
  1138. def __int__(self):
  1139. if self._mpf_ == fzero:
  1140. return 0
  1141. return int(mlib.to_int(self._mpf_)) # uses round_fast = round_down
  1142. def __eq__(self, other):
  1143. from sympy.logic.boolalg import Boolean
  1144. try:
  1145. other = _sympify(other)
  1146. except SympifyError:
  1147. return NotImplemented
  1148. if isinstance(other, Boolean):
  1149. return False
  1150. if other.is_NumberSymbol:
  1151. if other.is_irrational:
  1152. return False
  1153. return other.__eq__(self)
  1154. if other.is_Float:
  1155. # comparison is exact
  1156. # so Float(.1, 3) != Float(.1, 33)
  1157. return self._mpf_ == other._mpf_
  1158. if other.is_Rational:
  1159. return other.__eq__(self)
  1160. if other.is_Number:
  1161. # numbers should compare at the same precision;
  1162. # all _as_mpf_val routines should be sure to abide
  1163. # by the request to change the prec if necessary; if
  1164. # they don't, the equality test will fail since it compares
  1165. # the mpf tuples
  1166. ompf = other._as_mpf_val(self._prec)
  1167. return bool(mlib.mpf_eq(self._mpf_, ompf))
  1168. if not self:
  1169. return not other
  1170. return False # Float != non-Number
  1171. def __ne__(self, other):
  1172. return not self == other
  1173. def _Frel(self, other, op):
  1174. try:
  1175. other = _sympify(other)
  1176. except SympifyError:
  1177. return NotImplemented
  1178. if other.is_Rational:
  1179. # test self*other.q <?> other.p without losing precision
  1180. '''
  1181. >>> f = Float(.1,2)
  1182. >>> i = 1234567890
  1183. >>> (f*i)._mpf_
  1184. (0, 471, 18, 9)
  1185. >>> mlib.mpf_mul(f._mpf_, mlib.from_int(i))
  1186. (0, 505555550955, -12, 39)
  1187. '''
  1188. smpf = mlib.mpf_mul(self._mpf_, mlib.from_int(other.q))
  1189. ompf = mlib.from_int(other.p)
  1190. return _sympify(bool(op(smpf, ompf)))
  1191. elif other.is_Float:
  1192. return _sympify(bool(
  1193. op(self._mpf_, other._mpf_)))
  1194. elif other.is_comparable and other not in (
  1195. S.Infinity, S.NegativeInfinity):
  1196. other = other.evalf(prec_to_dps(self._prec))
  1197. if other._prec > 1:
  1198. if other.is_Number:
  1199. return _sympify(bool(
  1200. op(self._mpf_, other._as_mpf_val(self._prec))))
  1201. def __gt__(self, other):
  1202. if isinstance(other, NumberSymbol):
  1203. return other.__lt__(self)
  1204. rv = self._Frel(other, mlib.mpf_gt)
  1205. if rv is None:
  1206. return Expr.__gt__(self, other)
  1207. return rv
  1208. def __ge__(self, other):
  1209. if isinstance(other, NumberSymbol):
  1210. return other.__le__(self)
  1211. rv = self._Frel(other, mlib.mpf_ge)
  1212. if rv is None:
  1213. return Expr.__ge__(self, other)
  1214. return rv
  1215. def __lt__(self, other):
  1216. if isinstance(other, NumberSymbol):
  1217. return other.__gt__(self)
  1218. rv = self._Frel(other, mlib.mpf_lt)
  1219. if rv is None:
  1220. return Expr.__lt__(self, other)
  1221. return rv
  1222. def __le__(self, other):
  1223. if isinstance(other, NumberSymbol):
  1224. return other.__ge__(self)
  1225. rv = self._Frel(other, mlib.mpf_le)
  1226. if rv is None:
  1227. return Expr.__le__(self, other)
  1228. return rv
  1229. def __hash__(self):
  1230. return super().__hash__()
  1231. def epsilon_eq(self, other, epsilon="1e-15"):
  1232. return abs(self - other) < Float(epsilon)
  1233. def __format__(self, format_spec):
  1234. return format(decimal.Decimal(str(self)), format_spec)
  1235. # Add sympify converters
  1236. _sympy_converter[float] = _sympy_converter[decimal.Decimal] = Float
  1237. # this is here to work nicely in Sage
  1238. RealNumber = Float
  1239. class Rational(Number):
  1240. """Represents rational numbers (p/q) of any size.
  1241. Examples
  1242. ========
  1243. >>> from sympy import Rational, nsimplify, S, pi
  1244. >>> Rational(1, 2)
  1245. 1/2
  1246. Rational is unprejudiced in accepting input. If a float is passed, the
  1247. underlying value of the binary representation will be returned:
  1248. >>> Rational(.5)
  1249. 1/2
  1250. >>> Rational(.2)
  1251. 3602879701896397/18014398509481984
  1252. If the simpler representation of the float is desired then consider
  1253. limiting the denominator to the desired value or convert the float to
  1254. a string (which is roughly equivalent to limiting the denominator to
  1255. 10**12):
  1256. >>> Rational(str(.2))
  1257. 1/5
  1258. >>> Rational(.2).limit_denominator(10**12)
  1259. 1/5
  1260. An arbitrarily precise Rational is obtained when a string literal is
  1261. passed:
  1262. >>> Rational("1.23")
  1263. 123/100
  1264. >>> Rational('1e-2')
  1265. 1/100
  1266. >>> Rational(".1")
  1267. 1/10
  1268. >>> Rational('1e-2/3.2')
  1269. 1/320
  1270. The conversion of other types of strings can be handled by
  1271. the sympify() function, and conversion of floats to expressions
  1272. or simple fractions can be handled with nsimplify:
  1273. >>> S('.[3]') # repeating digits in brackets
  1274. 1/3
  1275. >>> S('3**2/10') # general expressions
  1276. 9/10
  1277. >>> nsimplify(.3) # numbers that have a simple form
  1278. 3/10
  1279. But if the input does not reduce to a literal Rational, an error will
  1280. be raised:
  1281. >>> Rational(pi)
  1282. Traceback (most recent call last):
  1283. ...
  1284. TypeError: invalid input: pi
  1285. Low-level
  1286. ---------
  1287. Access numerator and denominator as .p and .q:
  1288. >>> r = Rational(3, 4)
  1289. >>> r
  1290. 3/4
  1291. >>> r.p
  1292. 3
  1293. >>> r.q
  1294. 4
  1295. Note that p and q return integers (not SymPy Integers) so some care
  1296. is needed when using them in expressions:
  1297. >>> r.p/r.q
  1298. 0.75
  1299. If an unevaluated Rational is desired, ``gcd=1`` can be passed and
  1300. this will keep common divisors of the numerator and denominator
  1301. from being eliminated. It is not possible, however, to leave a
  1302. negative value in the denominator.
  1303. >>> Rational(2, 4, gcd=1)
  1304. 2/4
  1305. >>> Rational(2, -4, gcd=1).q
  1306. 4
  1307. See Also
  1308. ========
  1309. sympy.core.sympify.sympify, sympy.simplify.simplify.nsimplify
  1310. """
  1311. is_real = True
  1312. is_integer = False
  1313. is_rational = True
  1314. is_number = True
  1315. __slots__ = ('p', 'q')
  1316. p: int
  1317. q: int
  1318. is_Rational = True
  1319. @cacheit
  1320. def __new__(cls, p, q=None, gcd=None):
  1321. if q is None:
  1322. if isinstance(p, Rational):
  1323. return p
  1324. if isinstance(p, SYMPY_INTS):
  1325. pass
  1326. else:
  1327. if isinstance(p, (float, Float)):
  1328. return Rational(*_as_integer_ratio(p))
  1329. if not isinstance(p, str):
  1330. try:
  1331. p = sympify(p)
  1332. except (SympifyError, SyntaxError):
  1333. pass # error will raise below
  1334. else:
  1335. if p.count('/') > 1:
  1336. raise TypeError('invalid input: %s' % p)
  1337. p = p.replace(' ', '')
  1338. pq = p.rsplit('/', 1)
  1339. if len(pq) == 2:
  1340. p, q = pq
  1341. fp = fractions.Fraction(p)
  1342. fq = fractions.Fraction(q)
  1343. p = fp/fq
  1344. try:
  1345. p = fractions.Fraction(p)
  1346. except ValueError:
  1347. pass # error will raise below
  1348. else:
  1349. return Rational(p.numerator, p.denominator, 1)
  1350. if not isinstance(p, Rational):
  1351. raise TypeError('invalid input: %s' % p)
  1352. q = 1
  1353. gcd = 1
  1354. if not isinstance(p, SYMPY_INTS):
  1355. p = Rational(p)
  1356. q *= p.q
  1357. p = p.p
  1358. else:
  1359. p = int(p)
  1360. if not isinstance(q, SYMPY_INTS):
  1361. q = Rational(q)
  1362. p *= q.q
  1363. q = q.p
  1364. else:
  1365. q = int(q)
  1366. # p and q are now ints
  1367. if q == 0:
  1368. if p == 0:
  1369. if _errdict["divide"]:
  1370. raise ValueError("Indeterminate 0/0")
  1371. else:
  1372. return S.NaN
  1373. return S.ComplexInfinity
  1374. if q < 0:
  1375. q = -q
  1376. p = -p
  1377. if not gcd:
  1378. gcd = igcd(abs(p), q)
  1379. if gcd > 1:
  1380. p //= gcd
  1381. q //= gcd
  1382. if q == 1:
  1383. return Integer(p)
  1384. if p == 1 and q == 2:
  1385. return S.Half
  1386. obj = Expr.__new__(cls)
  1387. obj.p = p
  1388. obj.q = q
  1389. return obj
  1390. def limit_denominator(self, max_denominator=1000000):
  1391. """Closest Rational to self with denominator at most max_denominator.
  1392. Examples
  1393. ========
  1394. >>> from sympy import Rational
  1395. >>> Rational('3.141592653589793').limit_denominator(10)
  1396. 22/7
  1397. >>> Rational('3.141592653589793').limit_denominator(100)
  1398. 311/99
  1399. """
  1400. f = fractions.Fraction(self.p, self.q)
  1401. return Rational(f.limit_denominator(fractions.Fraction(int(max_denominator))))
  1402. def __getnewargs__(self):
  1403. return (self.p, self.q)
  1404. def _hashable_content(self):
  1405. return (self.p, self.q)
  1406. def _eval_is_positive(self):
  1407. return self.p > 0
  1408. def _eval_is_zero(self):
  1409. return self.p == 0
  1410. def __neg__(self):
  1411. return Rational(-self.p, self.q)
  1412. @_sympifyit('other', NotImplemented)
  1413. def __add__(self, other):
  1414. if global_parameters.evaluate:
  1415. if isinstance(other, Integer):
  1416. return Rational(self.p + self.q*other.p, self.q, 1)
  1417. elif isinstance(other, Rational):
  1418. #TODO: this can probably be optimized more
  1419. return Rational(self.p*other.q + self.q*other.p, self.q*other.q)
  1420. elif isinstance(other, Float):
  1421. return other + self
  1422. else:
  1423. return Number.__add__(self, other)
  1424. return Number.__add__(self, other)
  1425. __radd__ = __add__
  1426. @_sympifyit('other', NotImplemented)
  1427. def __sub__(self, other):
  1428. if global_parameters.evaluate:
  1429. if isinstance(other, Integer):
  1430. return Rational(self.p - self.q*other.p, self.q, 1)
  1431. elif isinstance(other, Rational):
  1432. return Rational(self.p*other.q - self.q*other.p, self.q*other.q)
  1433. elif isinstance(other, Float):
  1434. return -other + self
  1435. else:
  1436. return Number.__sub__(self, other)
  1437. return Number.__sub__(self, other)
  1438. @_sympifyit('other', NotImplemented)
  1439. def __rsub__(self, other):
  1440. if global_parameters.evaluate:
  1441. if isinstance(other, Integer):
  1442. return Rational(self.q*other.p - self.p, self.q, 1)
  1443. elif isinstance(other, Rational):
  1444. return Rational(self.q*other.p - self.p*other.q, self.q*other.q)
  1445. elif isinstance(other, Float):
  1446. return -self + other
  1447. else:
  1448. return Number.__rsub__(self, other)
  1449. return Number.__rsub__(self, other)
  1450. @_sympifyit('other', NotImplemented)
  1451. def __mul__(self, other):
  1452. if global_parameters.evaluate:
  1453. if isinstance(other, Integer):
  1454. return Rational(self.p*other.p, self.q, igcd(other.p, self.q))
  1455. elif isinstance(other, Rational):
  1456. return Rational(self.p*other.p, self.q*other.q, igcd(self.p, other.q)*igcd(self.q, other.p))
  1457. elif isinstance(other, Float):
  1458. return other*self
  1459. else:
  1460. return Number.__mul__(self, other)
  1461. return Number.__mul__(self, other)
  1462. __rmul__ = __mul__
  1463. @_sympifyit('other', NotImplemented)
  1464. def __truediv__(self, other):
  1465. if global_parameters.evaluate:
  1466. if isinstance(other, Integer):
  1467. if self.p and other.p == S.Zero:
  1468. return S.ComplexInfinity
  1469. else:
  1470. return Rational(self.p, self.q*other.p, igcd(self.p, other.p))
  1471. elif isinstance(other, Rational):
  1472. return Rational(self.p*other.q, self.q*other.p, igcd(self.p, other.p)*igcd(self.q, other.q))
  1473. elif isinstance(other, Float):
  1474. return self*(1/other)
  1475. else:
  1476. return Number.__truediv__(self, other)
  1477. return Number.__truediv__(self, other)
  1478. @_sympifyit('other', NotImplemented)
  1479. def __rtruediv__(self, other):
  1480. if global_parameters.evaluate:
  1481. if isinstance(other, Integer):
  1482. return Rational(other.p*self.q, self.p, igcd(self.p, other.p))
  1483. elif isinstance(other, Rational):
  1484. return Rational(other.p*self.q, other.q*self.p, igcd(self.p, other.p)*igcd(self.q, other.q))
  1485. elif isinstance(other, Float):
  1486. return other*(1/self)
  1487. else:
  1488. return Number.__rtruediv__(self, other)
  1489. return Number.__rtruediv__(self, other)
  1490. @_sympifyit('other', NotImplemented)
  1491. def __mod__(self, other):
  1492. if global_parameters.evaluate:
  1493. if isinstance(other, Rational):
  1494. n = (self.p*other.q) // (other.p*self.q)
  1495. return Rational(self.p*other.q - n*other.p*self.q, self.q*other.q)
  1496. if isinstance(other, Float):
  1497. # calculate mod with Rationals, *then* round the answer
  1498. return Float(self.__mod__(Rational(other)),
  1499. precision=other._prec)
  1500. return Number.__mod__(self, other)
  1501. return Number.__mod__(self, other)
  1502. @_sympifyit('other', NotImplemented)
  1503. def __rmod__(self, other):
  1504. if isinstance(other, Rational):
  1505. return Rational.__mod__(other, self)
  1506. return Number.__rmod__(self, other)
  1507. def _eval_power(self, expt):
  1508. if isinstance(expt, Number):
  1509. if isinstance(expt, Float):
  1510. return self._eval_evalf(expt._prec)**expt
  1511. if expt.is_extended_negative:
  1512. # (3/4)**-2 -> (4/3)**2
  1513. ne = -expt
  1514. if (ne is S.One):
  1515. return Rational(self.q, self.p)
  1516. if self.is_negative:
  1517. return S.NegativeOne**expt*Rational(self.q, -self.p)**ne
  1518. else:
  1519. return Rational(self.q, self.p)**ne
  1520. if expt is S.Infinity: # -oo already caught by test for negative
  1521. if self.p > self.q:
  1522. # (3/2)**oo -> oo
  1523. return S.Infinity
  1524. if self.p < -self.q:
  1525. # (-3/2)**oo -> oo + I*oo
  1526. return S.Infinity + S.Infinity*S.ImaginaryUnit
  1527. return S.Zero
  1528. if isinstance(expt, Integer):
  1529. # (4/3)**2 -> 4**2 / 3**2
  1530. return Rational(self.p**expt.p, self.q**expt.p, 1)
  1531. if isinstance(expt, Rational):
  1532. intpart = expt.p // expt.q
  1533. if intpart:
  1534. intpart += 1
  1535. remfracpart = intpart*expt.q - expt.p
  1536. ratfracpart = Rational(remfracpart, expt.q)
  1537. if self.p != 1:
  1538. return Integer(self.p)**expt*Integer(self.q)**ratfracpart*Rational(1, self.q**intpart, 1)
  1539. return Integer(self.q)**ratfracpart*Rational(1, self.q**intpart, 1)
  1540. else:
  1541. remfracpart = expt.q - expt.p
  1542. ratfracpart = Rational(remfracpart, expt.q)
  1543. if self.p != 1:
  1544. return Integer(self.p)**expt*Integer(self.q)**ratfracpart*Rational(1, self.q, 1)
  1545. return Integer(self.q)**ratfracpart*Rational(1, self.q, 1)
  1546. if self.is_extended_negative and expt.is_even:
  1547. return (-self)**expt
  1548. return
  1549. def _as_mpf_val(self, prec):
  1550. return mlib.from_rational(self.p, self.q, prec, rnd)
  1551. def _mpmath_(self, prec, rnd):
  1552. return mpmath.make_mpf(mlib.from_rational(self.p, self.q, prec, rnd))
  1553. def __abs__(self):
  1554. return Rational(abs(self.p), self.q)
  1555. def __int__(self):
  1556. p, q = self.p, self.q
  1557. if p < 0:
  1558. return -int(-p//q)
  1559. return int(p//q)
  1560. def floor(self):
  1561. return Integer(self.p // self.q)
  1562. def ceiling(self):
  1563. return -Integer(-self.p // self.q)
  1564. def __floor__(self):
  1565. return self.floor()
  1566. def __ceil__(self):
  1567. return self.ceiling()
  1568. def __eq__(self, other):
  1569. try:
  1570. other = _sympify(other)
  1571. except SympifyError:
  1572. return NotImplemented
  1573. if not isinstance(other, Number):
  1574. # S(0) == S.false is False
  1575. # S(0) == False is True
  1576. return False
  1577. if not self:
  1578. return not other
  1579. if other.is_NumberSymbol:
  1580. if other.is_irrational:
  1581. return False
  1582. return other.__eq__(self)
  1583. if other.is_Rational:
  1584. # a Rational is always in reduced form so will never be 2/4
  1585. # so we can just check equivalence of args
  1586. return self.p == other.p and self.q == other.q
  1587. if other.is_Float:
  1588. # all Floats have a denominator that is a power of 2
  1589. # so if self doesn't, it can't be equal to other
  1590. if self.q & (self.q - 1):
  1591. return False
  1592. s, m, t = other._mpf_[:3]
  1593. if s:
  1594. m = -m
  1595. if not t:
  1596. # other is an odd integer
  1597. if not self.is_Integer or self.is_even:
  1598. return False
  1599. return m == self.p
  1600. from .power import integer_log
  1601. if t > 0:
  1602. # other is an even integer
  1603. if not self.is_Integer:
  1604. return False
  1605. # does m*2**t == self.p
  1606. return self.p and not self.p % m and \
  1607. integer_log(self.p//m, 2) == (t, True)
  1608. # does non-integer s*m/2**-t = p/q?
  1609. if self.is_Integer:
  1610. return False
  1611. return m == self.p and integer_log(self.q, 2) == (-t, True)
  1612. return False
  1613. def __ne__(self, other):
  1614. return not self == other
  1615. def _Rrel(self, other, attr):
  1616. # if you want self < other, pass self, other, __gt__
  1617. try:
  1618. other = _sympify(other)
  1619. except SympifyError:
  1620. return NotImplemented
  1621. if other.is_Number:
  1622. op = None
  1623. s, o = self, other
  1624. if other.is_NumberSymbol:
  1625. op = getattr(o, attr)
  1626. elif other.is_Float:
  1627. op = getattr(o, attr)
  1628. elif other.is_Rational:
  1629. s, o = Integer(s.p*o.q), Integer(s.q*o.p)
  1630. op = getattr(o, attr)
  1631. if op:
  1632. return op(s)
  1633. if o.is_number and o.is_extended_real:
  1634. return Integer(s.p), s.q*o
  1635. def __gt__(self, other):
  1636. rv = self._Rrel(other, '__lt__')
  1637. if rv is None:
  1638. rv = self, other
  1639. elif not isinstance(rv, tuple):
  1640. return rv
  1641. return Expr.__gt__(*rv)
  1642. def __ge__(self, other):
  1643. rv = self._Rrel(other, '__le__')
  1644. if rv is None:
  1645. rv = self, other
  1646. elif not isinstance(rv, tuple):
  1647. return rv
  1648. return Expr.__ge__(*rv)
  1649. def __lt__(self, other):
  1650. rv = self._Rrel(other, '__gt__')
  1651. if rv is None:
  1652. rv = self, other
  1653. elif not isinstance(rv, tuple):
  1654. return rv
  1655. return Expr.__lt__(*rv)
  1656. def __le__(self, other):
  1657. rv = self._Rrel(other, '__ge__')
  1658. if rv is None:
  1659. rv = self, other
  1660. elif not isinstance(rv, tuple):
  1661. return rv
  1662. return Expr.__le__(*rv)
  1663. def __hash__(self):
  1664. return super().__hash__()
  1665. def factors(self, limit=None, use_trial=True, use_rho=False,
  1666. use_pm1=False, verbose=False, visual=False):
  1667. """A wrapper to factorint which return factors of self that are
  1668. smaller than limit (or cheap to compute). Special methods of
  1669. factoring are disabled by default so that only trial division is used.
  1670. """
  1671. from sympy.ntheory.factor_ import factorrat
  1672. return factorrat(self, limit=limit, use_trial=use_trial,
  1673. use_rho=use_rho, use_pm1=use_pm1,
  1674. verbose=verbose).copy()
  1675. @property
  1676. def numerator(self):
  1677. return self.p
  1678. @property
  1679. def denominator(self):
  1680. return self.q
  1681. @_sympifyit('other', NotImplemented)
  1682. def gcd(self, other):
  1683. if isinstance(other, Rational):
  1684. if other == S.Zero:
  1685. return other
  1686. return Rational(
  1687. igcd(self.p, other.p),
  1688. ilcm(self.q, other.q))
  1689. return Number.gcd(self, other)
  1690. @_sympifyit('other', NotImplemented)
  1691. def lcm(self, other):
  1692. if isinstance(other, Rational):
  1693. return Rational(
  1694. self.p // igcd(self.p, other.p) * other.p,
  1695. igcd(self.q, other.q))
  1696. return Number.lcm(self, other)
  1697. def as_numer_denom(self):
  1698. return Integer(self.p), Integer(self.q)
  1699. def as_content_primitive(self, radical=False, clear=True):
  1700. """Return the tuple (R, self/R) where R is the positive Rational
  1701. extracted from self.
  1702. Examples
  1703. ========
  1704. >>> from sympy import S
  1705. >>> (S(-3)/2).as_content_primitive()
  1706. (3/2, -1)
  1707. See docstring of Expr.as_content_primitive for more examples.
  1708. """
  1709. if self:
  1710. if self.is_positive:
  1711. return self, S.One
  1712. return -self, S.NegativeOne
  1713. return S.One, self
  1714. def as_coeff_Mul(self, rational=False):
  1715. """Efficiently extract the coefficient of a product. """
  1716. return self, S.One
  1717. def as_coeff_Add(self, rational=False):
  1718. """Efficiently extract the coefficient of a summation. """
  1719. return self, S.Zero
  1720. class Integer(Rational):
  1721. """Represents integer numbers of any size.
  1722. Examples
  1723. ========
  1724. >>> from sympy import Integer
  1725. >>> Integer(3)
  1726. 3
  1727. If a float or a rational is passed to Integer, the fractional part
  1728. will be discarded; the effect is of rounding toward zero.
  1729. >>> Integer(3.8)
  1730. 3
  1731. >>> Integer(-3.8)
  1732. -3
  1733. A string is acceptable input if it can be parsed as an integer:
  1734. >>> Integer("9" * 20)
  1735. 99999999999999999999
  1736. It is rarely needed to explicitly instantiate an Integer, because
  1737. Python integers are automatically converted to Integer when they
  1738. are used in SymPy expressions.
  1739. """
  1740. q = 1
  1741. is_integer = True
  1742. is_number = True
  1743. is_Integer = True
  1744. __slots__ = ('p',)
  1745. def _as_mpf_val(self, prec):
  1746. return mlib.from_int(self.p, prec, rnd)
  1747. def _mpmath_(self, prec, rnd):
  1748. return mpmath.make_mpf(self._as_mpf_val(prec))
  1749. @cacheit
  1750. def __new__(cls, i):
  1751. if isinstance(i, str):
  1752. i = i.replace(' ', '')
  1753. # whereas we cannot, in general, make a Rational from an
  1754. # arbitrary expression, we can make an Integer unambiguously
  1755. # (except when a non-integer expression happens to round to
  1756. # an integer). So we proceed by taking int() of the input and
  1757. # let the int routines determine whether the expression can
  1758. # be made into an int or whether an error should be raised.
  1759. try:
  1760. ival = int(i)
  1761. except TypeError:
  1762. raise TypeError(
  1763. "Argument of Integer should be of numeric type, got %s." % i)
  1764. # We only work with well-behaved integer types. This converts, for
  1765. # example, numpy.int32 instances.
  1766. if ival == 1:
  1767. return S.One
  1768. if ival == -1:
  1769. return S.NegativeOne
  1770. if ival == 0:
  1771. return S.Zero
  1772. obj = Expr.__new__(cls)
  1773. obj.p = ival
  1774. return obj
  1775. def __getnewargs__(self):
  1776. return (self.p,)
  1777. # Arithmetic operations are here for efficiency
  1778. def __int__(self):
  1779. return self.p
  1780. def floor(self):
  1781. return Integer(self.p)
  1782. def ceiling(self):
  1783. return Integer(self.p)
  1784. def __floor__(self):
  1785. return self.floor()
  1786. def __ceil__(self):
  1787. return self.ceiling()
  1788. def __neg__(self):
  1789. return Integer(-self.p)
  1790. def __abs__(self):
  1791. if self.p >= 0:
  1792. return self
  1793. else:
  1794. return Integer(-self.p)
  1795. def __divmod__(self, other):
  1796. if isinstance(other, Integer) and global_parameters.evaluate:
  1797. return Tuple(*(divmod(self.p, other.p)))
  1798. else:
  1799. return Number.__divmod__(self, other)
  1800. def __rdivmod__(self, other):
  1801. if isinstance(other, int) and global_parameters.evaluate:
  1802. return Tuple(*(divmod(other, self.p)))
  1803. else:
  1804. try:
  1805. other = Number(other)
  1806. except TypeError:
  1807. msg = "unsupported operand type(s) for divmod(): '%s' and '%s'"
  1808. oname = type(other).__name__
  1809. sname = type(self).__name__
  1810. raise TypeError(msg % (oname, sname))
  1811. return Number.__divmod__(other, self)
  1812. # TODO make it decorator + bytecodehacks?
  1813. def __add__(self, other):
  1814. if global_parameters.evaluate:
  1815. if isinstance(other, int):
  1816. return Integer(self.p + other)
  1817. elif isinstance(other, Integer):
  1818. return Integer(self.p + other.p)
  1819. elif isinstance(other, Rational):
  1820. return Rational(self.p*other.q + other.p, other.q, 1)
  1821. return Rational.__add__(self, other)
  1822. else:
  1823. return Add(self, other)
  1824. def __radd__(self, other):
  1825. if global_parameters.evaluate:
  1826. if isinstance(other, int):
  1827. return Integer(other + self.p)
  1828. elif isinstance(other, Rational):
  1829. return Rational(other.p + self.p*other.q, other.q, 1)
  1830. return Rational.__radd__(self, other)
  1831. return Rational.__radd__(self, other)
  1832. def __sub__(self, other):
  1833. if global_parameters.evaluate:
  1834. if isinstance(other, int):
  1835. return Integer(self.p - other)
  1836. elif isinstance(other, Integer):
  1837. return Integer(self.p - other.p)
  1838. elif isinstance(other, Rational):
  1839. return Rational(self.p*other.q - other.p, other.q, 1)
  1840. return Rational.__sub__(self, other)
  1841. return Rational.__sub__(self, other)
  1842. def __rsub__(self, other):
  1843. if global_parameters.evaluate:
  1844. if isinstance(other, int):
  1845. return Integer(other - self.p)
  1846. elif isinstance(other, Rational):
  1847. return Rational(other.p - self.p*other.q, other.q, 1)
  1848. return Rational.__rsub__(self, other)
  1849. return Rational.__rsub__(self, other)
  1850. def __mul__(self, other):
  1851. if global_parameters.evaluate:
  1852. if isinstance(other, int):
  1853. return Integer(self.p*other)
  1854. elif isinstance(other, Integer):
  1855. return Integer(self.p*other.p)
  1856. elif isinstance(other, Rational):
  1857. return Rational(self.p*other.p, other.q, igcd(self.p, other.q))
  1858. return Rational.__mul__(self, other)
  1859. return Rational.__mul__(self, other)
  1860. def __rmul__(self, other):
  1861. if global_parameters.evaluate:
  1862. if isinstance(other, int):
  1863. return Integer(other*self.p)
  1864. elif isinstance(other, Rational):
  1865. return Rational(other.p*self.p, other.q, igcd(self.p, other.q))
  1866. return Rational.__rmul__(self, other)
  1867. return Rational.__rmul__(self, other)
  1868. def __mod__(self, other):
  1869. if global_parameters.evaluate:
  1870. if isinstance(other, int):
  1871. return Integer(self.p % other)
  1872. elif isinstance(other, Integer):
  1873. return Integer(self.p % other.p)
  1874. return Rational.__mod__(self, other)
  1875. return Rational.__mod__(self, other)
  1876. def __rmod__(self, other):
  1877. if global_parameters.evaluate:
  1878. if isinstance(other, int):
  1879. return Integer(other % self.p)
  1880. elif isinstance(other, Integer):
  1881. return Integer(other.p % self.p)
  1882. return Rational.__rmod__(self, other)
  1883. return Rational.__rmod__(self, other)
  1884. def __eq__(self, other):
  1885. if isinstance(other, int):
  1886. return (self.p == other)
  1887. elif isinstance(other, Integer):
  1888. return (self.p == other.p)
  1889. return Rational.__eq__(self, other)
  1890. def __ne__(self, other):
  1891. return not self == other
  1892. def __gt__(self, other):
  1893. try:
  1894. other = _sympify(other)
  1895. except SympifyError:
  1896. return NotImplemented
  1897. if other.is_Integer:
  1898. return _sympify(self.p > other.p)
  1899. return Rational.__gt__(self, other)
  1900. def __lt__(self, other):
  1901. try:
  1902. other = _sympify(other)
  1903. except SympifyError:
  1904. return NotImplemented
  1905. if other.is_Integer:
  1906. return _sympify(self.p < other.p)
  1907. return Rational.__lt__(self, other)
  1908. def __ge__(self, other):
  1909. try:
  1910. other = _sympify(other)
  1911. except SympifyError:
  1912. return NotImplemented
  1913. if other.is_Integer:
  1914. return _sympify(self.p >= other.p)
  1915. return Rational.__ge__(self, other)
  1916. def __le__(self, other):
  1917. try:
  1918. other = _sympify(other)
  1919. except SympifyError:
  1920. return NotImplemented
  1921. if other.is_Integer:
  1922. return _sympify(self.p <= other.p)
  1923. return Rational.__le__(self, other)
  1924. def __hash__(self):
  1925. return hash(self.p)
  1926. def __index__(self):
  1927. return self.p
  1928. ########################################
  1929. def _eval_is_odd(self):
  1930. return bool(self.p % 2)
  1931. def _eval_power(self, expt):
  1932. """
  1933. Tries to do some simplifications on self**expt
  1934. Returns None if no further simplifications can be done.
  1935. Explanation
  1936. ===========
  1937. When exponent is a fraction (so we have for example a square root),
  1938. we try to find a simpler representation by factoring the argument
  1939. up to factors of 2**15, e.g.
  1940. - sqrt(4) becomes 2
  1941. - sqrt(-4) becomes 2*I
  1942. - (2**(3+7)*3**(6+7))**Rational(1,7) becomes 6*18**(3/7)
  1943. Further simplification would require a special call to factorint on
  1944. the argument which is not done here for sake of speed.
  1945. """
  1946. from sympy.ntheory.factor_ import perfect_power
  1947. if expt is S.Infinity:
  1948. if self.p > S.One:
  1949. return S.Infinity
  1950. # cases -1, 0, 1 are done in their respective classes
  1951. return S.Infinity + S.ImaginaryUnit*S.Infinity
  1952. if expt is S.NegativeInfinity:
  1953. return Rational(1, self, 1)**S.Infinity
  1954. if not isinstance(expt, Number):
  1955. # simplify when expt is even
  1956. # (-2)**k --> 2**k
  1957. if self.is_negative and expt.is_even:
  1958. return (-self)**expt
  1959. if isinstance(expt, Float):
  1960. # Rational knows how to exponentiate by a Float
  1961. return super()._eval_power(expt)
  1962. if not isinstance(expt, Rational):
  1963. return
  1964. if expt is S.Half and self.is_negative:
  1965. # we extract I for this special case since everyone is doing so
  1966. return S.ImaginaryUnit*Pow(-self, expt)
  1967. if expt.is_negative:
  1968. # invert base and change sign on exponent
  1969. ne = -expt
  1970. if self.is_negative:
  1971. return S.NegativeOne**expt*Rational(1, -self, 1)**ne
  1972. else:
  1973. return Rational(1, self.p, 1)**ne
  1974. # see if base is a perfect root, sqrt(4) --> 2
  1975. x, xexact = integer_nthroot(abs(self.p), expt.q)
  1976. if xexact:
  1977. # if it's a perfect root we've finished
  1978. result = Integer(x**abs(expt.p))
  1979. if self.is_negative:
  1980. result *= S.NegativeOne**expt
  1981. return result
  1982. # The following is an algorithm where we collect perfect roots
  1983. # from the factors of base.
  1984. # if it's not an nth root, it still might be a perfect power
  1985. b_pos = int(abs(self.p))
  1986. p = perfect_power(b_pos)
  1987. if p is not False:
  1988. dict = {p[0]: p[1]}
  1989. else:
  1990. dict = Integer(b_pos).factors(limit=2**15)
  1991. # now process the dict of factors
  1992. out_int = 1 # integer part
  1993. out_rad = 1 # extracted radicals
  1994. sqr_int = 1
  1995. sqr_gcd = 0
  1996. sqr_dict = {}
  1997. for prime, exponent in dict.items():
  1998. exponent *= expt.p
  1999. # remove multiples of expt.q: (2**12)**(1/10) -> 2*(2**2)**(1/10)
  2000. div_e, div_m = divmod(exponent, expt.q)
  2001. if div_e > 0:
  2002. out_int *= prime**div_e
  2003. if div_m > 0:
  2004. # see if the reduced exponent shares a gcd with e.q
  2005. # (2**2)**(1/10) -> 2**(1/5)
  2006. g = igcd(div_m, expt.q)
  2007. if g != 1:
  2008. out_rad *= Pow(prime, Rational(div_m//g, expt.q//g, 1))
  2009. else:
  2010. sqr_dict[prime] = div_m
  2011. # identify gcd of remaining powers
  2012. for p, ex in sqr_dict.items():
  2013. if sqr_gcd == 0:
  2014. sqr_gcd = ex
  2015. else:
  2016. sqr_gcd = igcd(sqr_gcd, ex)
  2017. if sqr_gcd == 1:
  2018. break
  2019. for k, v in sqr_dict.items():
  2020. sqr_int *= k**(v//sqr_gcd)
  2021. if sqr_int == b_pos and out_int == 1 and out_rad == 1:
  2022. result = None
  2023. else:
  2024. result = out_int*out_rad*Pow(sqr_int, Rational(sqr_gcd, expt.q))
  2025. if self.is_negative:
  2026. result *= Pow(S.NegativeOne, expt)
  2027. return result
  2028. def _eval_is_prime(self):
  2029. from sympy.ntheory.primetest import isprime
  2030. return isprime(self)
  2031. def _eval_is_composite(self):
  2032. if self > 1:
  2033. return fuzzy_not(self.is_prime)
  2034. else:
  2035. return False
  2036. def as_numer_denom(self):
  2037. return self, S.One
  2038. @_sympifyit('other', NotImplemented)
  2039. def __floordiv__(self, other):
  2040. if not isinstance(other, Expr):
  2041. return NotImplemented
  2042. if isinstance(other, Integer):
  2043. return Integer(self.p // other)
  2044. return Integer(divmod(self, other)[0])
  2045. def __rfloordiv__(self, other):
  2046. return Integer(Integer(other).p // self.p)
  2047. # These bitwise operations (__lshift__, __rlshift__, ..., __invert__) are defined
  2048. # for Integer only and not for general SymPy expressions. This is to achieve
  2049. # compatibility with the numbers.Integral ABC which only defines these operations
  2050. # among instances of numbers.Integral. Therefore, these methods check explicitly for
  2051. # integer types rather than using sympify because they should not accept arbitrary
  2052. # symbolic expressions and there is no symbolic analogue of numbers.Integral's
  2053. # bitwise operations.
  2054. def __lshift__(self, other):
  2055. if isinstance(other, (int, Integer, numbers.Integral)):
  2056. return Integer(self.p << int(other))
  2057. else:
  2058. return NotImplemented
  2059. def __rlshift__(self, other):
  2060. if isinstance(other, (int, numbers.Integral)):
  2061. return Integer(int(other) << self.p)
  2062. else:
  2063. return NotImplemented
  2064. def __rshift__(self, other):
  2065. if isinstance(other, (int, Integer, numbers.Integral)):
  2066. return Integer(self.p >> int(other))
  2067. else:
  2068. return NotImplemented
  2069. def __rrshift__(self, other):
  2070. if isinstance(other, (int, numbers.Integral)):
  2071. return Integer(int(other) >> self.p)
  2072. else:
  2073. return NotImplemented
  2074. def __and__(self, other):
  2075. if isinstance(other, (int, Integer, numbers.Integral)):
  2076. return Integer(self.p & int(other))
  2077. else:
  2078. return NotImplemented
  2079. def __rand__(self, other):
  2080. if isinstance(other, (int, numbers.Integral)):
  2081. return Integer(int(other) & self.p)
  2082. else:
  2083. return NotImplemented
  2084. def __xor__(self, other):
  2085. if isinstance(other, (int, Integer, numbers.Integral)):
  2086. return Integer(self.p ^ int(other))
  2087. else:
  2088. return NotImplemented
  2089. def __rxor__(self, other):
  2090. if isinstance(other, (int, numbers.Integral)):
  2091. return Integer(int(other) ^ self.p)
  2092. else:
  2093. return NotImplemented
  2094. def __or__(self, other):
  2095. if isinstance(other, (int, Integer, numbers.Integral)):
  2096. return Integer(self.p | int(other))
  2097. else:
  2098. return NotImplemented
  2099. def __ror__(self, other):
  2100. if isinstance(other, (int, numbers.Integral)):
  2101. return Integer(int(other) | self.p)
  2102. else:
  2103. return NotImplemented
  2104. def __invert__(self):
  2105. return Integer(~self.p)
  2106. # Add sympify converters
  2107. _sympy_converter[int] = Integer
  2108. class AlgebraicNumber(Expr):
  2109. r"""
  2110. Class for representing algebraic numbers in SymPy.
  2111. Symbolically, an instance of this class represents an element
  2112. $\alpha \in \mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$. That is, the
  2113. algebraic number $\alpha$ is represented as an element of a particular
  2114. number field $\mathbb{Q}(\theta)$, with a particular embedding of this
  2115. field into the complex numbers.
  2116. Formally, the primitive element $\theta$ is given by two data points: (1)
  2117. its minimal polynomial (which defines $\mathbb{Q}(\theta)$), and (2) a
  2118. particular complex number that is a root of this polynomial (which defines
  2119. the embedding $\mathbb{Q}(\theta) \hookrightarrow \mathbb{C}$). Finally,
  2120. the algebraic number $\alpha$ which we represent is then given by the
  2121. coefficients of a polynomial in $\theta$.
  2122. """
  2123. __slots__ = ('rep', 'root', 'alias', 'minpoly', '_own_minpoly')
  2124. is_AlgebraicNumber = True
  2125. is_algebraic = True
  2126. is_number = True
  2127. kind = NumberKind
  2128. # Optional alias symbol is not free.
  2129. # Actually, alias should be a Str, but some methods
  2130. # expect that it be an instance of Expr.
  2131. free_symbols: tSet[Basic] = set()
  2132. def __new__(cls, expr, coeffs=None, alias=None, **args):
  2133. r"""
  2134. Construct a new algebraic number $\alpha$ belonging to a number field
  2135. $k = \mathbb{Q}(\theta)$.
  2136. There are four instance attributes to be determined:
  2137. =========== ============================================================================
  2138. Attribute Type/Meaning
  2139. =========== ============================================================================
  2140. ``root`` :py:class:`~.Expr` for $\theta$ as a complex number
  2141. ``minpoly`` :py:class:`~.Poly`, the minimal polynomial of $\theta$
  2142. ``rep`` :py:class:`~sympy.polys.polyclasses.DMP` giving $\alpha$ as poly in $\theta$
  2143. ``alias`` :py:class:`~.Symbol` for $\theta$, or ``None``
  2144. =========== ============================================================================
  2145. See Parameters section for how they are determined.
  2146. Parameters
  2147. ==========
  2148. expr : :py:class:`~.Expr`, or pair $(m, r)$
  2149. There are three distinct modes of construction, depending on what
  2150. is passed as *expr*.
  2151. **(1)** *expr* is an :py:class:`~.AlgebraicNumber`:
  2152. In this case we begin by copying all four instance attributes from
  2153. *expr*. If *coeffs* were also given, we compose the two coeff
  2154. polynomials (see below). If an *alias* was given, it overrides.
  2155. **(2)** *expr* is any other type of :py:class:`~.Expr`:
  2156. Then ``root`` will equal *expr*. Therefore it
  2157. must express an algebraic quantity, and we will compute its
  2158. ``minpoly``.
  2159. **(3)** *expr* is an ordered pair $(m, r)$ giving the
  2160. ``minpoly`` $m$, and a ``root`` $r$ thereof, which together
  2161. define $\theta$. In this case $m$ may be either a univariate
  2162. :py:class:`~.Poly` or any :py:class:`~.Expr` which represents the
  2163. same, while $r$ must be some :py:class:`~.Expr` representing a
  2164. complex number that is a root of $m$, including both explicit
  2165. expressions in radicals, and instances of
  2166. :py:class:`~.ComplexRootOf` or :py:class:`~.AlgebraicNumber`.
  2167. coeffs : list, :py:class:`~.ANP`, None, optional (default=None)
  2168. This defines ``rep``, giving the algebraic number $\alpha$ as a
  2169. polynomial in $\theta$.
  2170. If a list, the elements should be integers or rational numbers.
  2171. If an :py:class:`~.ANP`, we take its coefficients (using its
  2172. :py:meth:`~.ANP.to_list()` method). If ``None``, then the list of
  2173. coefficients defaults to ``[1, 0]``, meaning that $\alpha = \theta$
  2174. is the primitive element of the field.
  2175. If *expr* was an :py:class:`~.AlgebraicNumber`, let $g(x)$ be its
  2176. ``rep`` polynomial, and let $f(x)$ be the polynomial defined by
  2177. *coeffs*. Then ``self.rep`` will represent the composition
  2178. $(f \circ g)(x)$.
  2179. alias : str, :py:class:`~.Symbol`, None, optional (default=None)
  2180. This is a way to provide a name for the primitive element. We
  2181. described several ways in which the *expr* argument can define the
  2182. value of the primitive element, but none of these methods gave it
  2183. a name. Here, for example, *alias* could be set as
  2184. ``Symbol('theta')``, in order to make this symbol appear when
  2185. $\alpha$ is printed, or rendered as a polynomial, using the
  2186. :py:meth:`~.as_poly()` method.
  2187. Examples
  2188. ========
  2189. Recall that we are constructing an algebraic number as a field element
  2190. $\alpha \in \mathbb{Q}(\theta)$.
  2191. >>> from sympy import AlgebraicNumber, sqrt, CRootOf, S
  2192. >>> from sympy.abc import x
  2193. Example (1): $\alpha = \theta = \sqrt{2}$
  2194. >>> a1 = AlgebraicNumber(sqrt(2))
  2195. >>> a1.minpoly_of_element().as_expr(x)
  2196. x**2 - 2
  2197. >>> a1.evalf(10)
  2198. 1.414213562
  2199. Example (2): $\alpha = 3 \sqrt{2} - 5$, $\theta = \sqrt{2}$. We can
  2200. either build on the last example:
  2201. >>> a2 = AlgebraicNumber(a1, [3, -5])
  2202. >>> a2.as_expr()
  2203. -5 + 3*sqrt(2)
  2204. or start from scratch:
  2205. >>> a2 = AlgebraicNumber(sqrt(2), [3, -5])
  2206. >>> a2.as_expr()
  2207. -5 + 3*sqrt(2)
  2208. Example (3): $\alpha = 6 \sqrt{2} - 11$, $\theta = \sqrt{2}$. Again we
  2209. can build on the previous example, and we see that the coeff polys are
  2210. composed:
  2211. >>> a3 = AlgebraicNumber(a2, [2, -1])
  2212. >>> a3.as_expr()
  2213. -11 + 6*sqrt(2)
  2214. reflecting the fact that $(2x - 1) \circ (3x - 5) = 6x - 11$.
  2215. Example (4): $\alpha = \sqrt{2}$, $\theta = \sqrt{2} + \sqrt{3}$. The
  2216. easiest way is to use the :py:func:`~.to_number_field()` function:
  2217. >>> from sympy import to_number_field
  2218. >>> a4 = to_number_field(sqrt(2), sqrt(2) + sqrt(3))
  2219. >>> a4.minpoly_of_element().as_expr(x)
  2220. x**2 - 2
  2221. >>> a4.to_root()
  2222. sqrt(2)
  2223. >>> a4.primitive_element()
  2224. sqrt(2) + sqrt(3)
  2225. >>> a4.coeffs()
  2226. [1/2, 0, -9/2, 0]
  2227. but if you already knew the right coefficients, you could construct it
  2228. directly:
  2229. >>> a4 = AlgebraicNumber(sqrt(2) + sqrt(3), [S(1)/2, 0, S(-9)/2, 0])
  2230. >>> a4.to_root()
  2231. sqrt(2)
  2232. >>> a4.primitive_element()
  2233. sqrt(2) + sqrt(3)
  2234. Example (5): Construct the Golden Ratio as an element of the 5th
  2235. cyclotomic field, supposing we already know its coefficients. This time
  2236. we introduce the alias $\zeta$ for the primitive element of the field:
  2237. >>> from sympy import cyclotomic_poly
  2238. >>> from sympy.abc import zeta
  2239. >>> a5 = AlgebraicNumber(CRootOf(cyclotomic_poly(5), -1),
  2240. ... [-1, -1, 0, 0], alias=zeta)
  2241. >>> a5.as_poly().as_expr()
  2242. -zeta**3 - zeta**2
  2243. >>> a5.evalf()
  2244. 1.61803398874989
  2245. (The index ``-1`` to ``CRootOf`` selects the complex root with the
  2246. largest real and imaginary parts, which in this case is
  2247. $\mathrm{e}^{2i\pi/5}$. See :py:class:`~.ComplexRootOf`.)
  2248. Example (6): Building on the last example, construct the number
  2249. $2 \phi \in \mathbb{Q}(\phi)$, where $\phi$ is the Golden Ratio:
  2250. >>> from sympy.abc import phi
  2251. >>> a6 = AlgebraicNumber(a5.to_root(), coeffs=[2, 0], alias=phi)
  2252. >>> a6.as_poly().as_expr()
  2253. 2*phi
  2254. >>> a6.primitive_element().evalf()
  2255. 1.61803398874989
  2256. Note that we needed to use ``a5.to_root()``, since passing ``a5`` as
  2257. the first argument would have constructed the number $2 \phi$ as an
  2258. element of the field $\mathbb{Q}(\zeta)$:
  2259. >>> a6_wrong = AlgebraicNumber(a5, coeffs=[2, 0])
  2260. >>> a6_wrong.as_poly().as_expr()
  2261. -2*zeta**3 - 2*zeta**2
  2262. >>> a6_wrong.primitive_element().evalf()
  2263. 0.309016994374947 + 0.951056516295154*I
  2264. """
  2265. from sympy.polys.polyclasses import ANP, DMP
  2266. from sympy.polys.numberfields import minimal_polynomial
  2267. expr = sympify(expr)
  2268. rep0 = None
  2269. alias0 = None
  2270. if isinstance(expr, (tuple, Tuple)):
  2271. minpoly, root = expr
  2272. if not minpoly.is_Poly:
  2273. from sympy.polys.polytools import Poly
  2274. minpoly = Poly(minpoly)
  2275. elif expr.is_AlgebraicNumber:
  2276. minpoly, root, rep0, alias0 = (expr.minpoly, expr.root,
  2277. expr.rep, expr.alias)
  2278. else:
  2279. minpoly, root = minimal_polynomial(
  2280. expr, args.get('gen'), polys=True), expr
  2281. dom = minpoly.get_domain()
  2282. if coeffs is not None:
  2283. if not isinstance(coeffs, ANP):
  2284. rep = DMP.from_sympy_list(sympify(coeffs), 0, dom)
  2285. scoeffs = Tuple(*coeffs)
  2286. else:
  2287. rep = DMP.from_list(coeffs.to_list(), 0, dom)
  2288. scoeffs = Tuple(*coeffs.to_list())
  2289. else:
  2290. rep = DMP.from_list([1, 0], 0, dom)
  2291. scoeffs = Tuple(1, 0)
  2292. if rep0 is not None:
  2293. from sympy.polys.densetools import dup_compose
  2294. c = dup_compose(rep.rep, rep0.rep, dom)
  2295. rep = DMP.from_list(c, 0, dom)
  2296. scoeffs = Tuple(*c)
  2297. if rep.degree() >= minpoly.degree():
  2298. rep = rep.rem(minpoly.rep)
  2299. sargs = (root, scoeffs)
  2300. alias = alias or alias0
  2301. if alias is not None:
  2302. from .symbol import Symbol
  2303. if not isinstance(alias, Symbol):
  2304. alias = Symbol(alias)
  2305. sargs = sargs + (alias,)
  2306. obj = Expr.__new__(cls, *sargs)
  2307. obj.rep = rep
  2308. obj.root = root
  2309. obj.alias = alias
  2310. obj.minpoly = minpoly
  2311. obj._own_minpoly = None
  2312. return obj
  2313. def __hash__(self):
  2314. return super().__hash__()
  2315. def _eval_evalf(self, prec):
  2316. return self.as_expr()._evalf(prec)
  2317. @property
  2318. def is_aliased(self):
  2319. """Returns ``True`` if ``alias`` was set. """
  2320. return self.alias is not None
  2321. def as_poly(self, x=None):
  2322. """Create a Poly instance from ``self``. """
  2323. from sympy.polys.polytools import Poly, PurePoly
  2324. if x is not None:
  2325. return Poly.new(self.rep, x)
  2326. else:
  2327. if self.alias is not None:
  2328. return Poly.new(self.rep, self.alias)
  2329. else:
  2330. from .symbol import Dummy
  2331. return PurePoly.new(self.rep, Dummy('x'))
  2332. def as_expr(self, x=None):
  2333. """Create a Basic expression from ``self``. """
  2334. return self.as_poly(x or self.root).as_expr().expand()
  2335. def coeffs(self):
  2336. """Returns all SymPy coefficients of an algebraic number. """
  2337. return [ self.rep.dom.to_sympy(c) for c in self.rep.all_coeffs() ]
  2338. def native_coeffs(self):
  2339. """Returns all native coefficients of an algebraic number. """
  2340. return self.rep.all_coeffs()
  2341. def to_algebraic_integer(self):
  2342. """Convert ``self`` to an algebraic integer. """
  2343. from sympy.polys.polytools import Poly
  2344. f = self.minpoly
  2345. if f.LC() == 1:
  2346. return self
  2347. coeff = f.LC()**(f.degree() - 1)
  2348. poly = f.compose(Poly(f.gen/f.LC()))
  2349. minpoly = poly*coeff
  2350. root = f.LC()*self.root
  2351. return AlgebraicNumber((minpoly, root), self.coeffs())
  2352. def _eval_simplify(self, **kwargs):
  2353. from sympy.polys.rootoftools import CRootOf
  2354. from sympy.polys import minpoly
  2355. measure, ratio = kwargs['measure'], kwargs['ratio']
  2356. for r in [r for r in self.minpoly.all_roots() if r.func != CRootOf]:
  2357. if minpoly(self.root - r).is_Symbol:
  2358. # use the matching root if it's simpler
  2359. if measure(r) < ratio*measure(self.root):
  2360. return AlgebraicNumber(r)
  2361. return self
  2362. def field_element(self, coeffs):
  2363. r"""
  2364. Form another element of the same number field.
  2365. Explanation
  2366. ===========
  2367. If we represent $\alpha \in \mathbb{Q}(\theta)$, form another element
  2368. $\beta \in \mathbb{Q}(\theta)$ of the same number field.
  2369. Parameters
  2370. ==========
  2371. coeffs : list, :py:class:`~.ANP`
  2372. Like the *coeffs* arg to the class
  2373. :py:meth:`constructor<.AlgebraicNumber.__new__>`, defines the
  2374. new element as a polynomial in the primitive element.
  2375. If a list, the elements should be integers or rational numbers.
  2376. If an :py:class:`~.ANP`, we take its coefficients (using its
  2377. :py:meth:`~.ANP.to_list()` method).
  2378. Examples
  2379. ========
  2380. >>> from sympy import AlgebraicNumber, sqrt
  2381. >>> a = AlgebraicNumber(sqrt(5), [-1, 1])
  2382. >>> b = a.field_element([3, 2])
  2383. >>> print(a)
  2384. 1 - sqrt(5)
  2385. >>> print(b)
  2386. 2 + 3*sqrt(5)
  2387. >>> print(b.primitive_element() == a.primitive_element())
  2388. True
  2389. See Also
  2390. ========
  2391. .AlgebraicNumber.__new__()
  2392. """
  2393. return AlgebraicNumber(
  2394. (self.minpoly, self.root), coeffs=coeffs, alias=self.alias)
  2395. @property
  2396. def is_primitive_element(self):
  2397. r"""
  2398. Say whether this algebraic number $\alpha \in \mathbb{Q}(\theta)$ is
  2399. equal to the primitive element $\theta$ for its field.
  2400. """
  2401. c = self.coeffs()
  2402. # Second case occurs if self.minpoly is linear:
  2403. return c == [1, 0] or c == [self.root]
  2404. def primitive_element(self):
  2405. r"""
  2406. Get the primitive element $\theta$ for the number field
  2407. $\mathbb{Q}(\theta)$ to which this algebraic number $\alpha$ belongs.
  2408. Returns
  2409. =======
  2410. AlgebraicNumber
  2411. """
  2412. if self.is_primitive_element:
  2413. return self
  2414. return self.field_element([1, 0])
  2415. def to_primitive_element(self, radicals=True):
  2416. r"""
  2417. Convert ``self`` to an :py:class:`~.AlgebraicNumber` instance that is
  2418. equal to its own primitive element.
  2419. Explanation
  2420. ===========
  2421. If we represent $\alpha \in \mathbb{Q}(\theta)$, $\alpha \neq \theta$,
  2422. construct a new :py:class:`~.AlgebraicNumber` that represents
  2423. $\alpha \in \mathbb{Q}(\alpha)$.
  2424. Examples
  2425. ========
  2426. >>> from sympy import sqrt, to_number_field
  2427. >>> from sympy.abc import x
  2428. >>> a = to_number_field(sqrt(2), sqrt(2) + sqrt(3))
  2429. The :py:class:`~.AlgebraicNumber` ``a`` represents the number
  2430. $\sqrt{2}$ in the field $\mathbb{Q}(\sqrt{2} + \sqrt{3})$. Rendering
  2431. ``a`` as a polynomial,
  2432. >>> a.as_poly().as_expr(x)
  2433. x**3/2 - 9*x/2
  2434. reflects the fact that $\sqrt{2} = \theta^3/2 - 9 \theta/2$, where
  2435. $\theta = \sqrt{2} + \sqrt{3}$.
  2436. ``a`` is not equal to its own primitive element. Its minpoly
  2437. >>> a.minpoly.as_poly().as_expr(x)
  2438. x**4 - 10*x**2 + 1
  2439. is that of $\theta$.
  2440. Converting to a primitive element,
  2441. >>> a_prim = a.to_primitive_element()
  2442. >>> a_prim.minpoly.as_poly().as_expr(x)
  2443. x**2 - 2
  2444. we obtain an :py:class:`~.AlgebraicNumber` whose ``minpoly`` is that of
  2445. the number itself.
  2446. Parameters
  2447. ==========
  2448. radicals : boolean, optional (default=True)
  2449. If ``True``, then we will try to return an
  2450. :py:class:`~.AlgebraicNumber` whose ``root`` is an expression
  2451. in radicals. If that is not possible (or if *radicals* is
  2452. ``False``), ``root`` will be a :py:class:`~.ComplexRootOf`.
  2453. Returns
  2454. =======
  2455. AlgebraicNumber
  2456. See Also
  2457. ========
  2458. is_primitive_element
  2459. """
  2460. if self.is_primitive_element:
  2461. return self
  2462. m = self.minpoly_of_element()
  2463. r = self.to_root(radicals=radicals)
  2464. return AlgebraicNumber((m, r))
  2465. def minpoly_of_element(self):
  2466. r"""
  2467. Compute the minimal polynomial for this algebraic number.
  2468. Explanation
  2469. ===========
  2470. Recall that we represent an element $\alpha \in \mathbb{Q}(\theta)$.
  2471. Our instance attribute ``self.minpoly`` is the minimal polynomial for
  2472. our primitive element $\theta$. This method computes the minimal
  2473. polynomial for $\alpha$.
  2474. """
  2475. if self._own_minpoly is None:
  2476. if self.is_primitive_element:
  2477. self._own_minpoly = self.minpoly
  2478. else:
  2479. from sympy.polys.numberfields.minpoly import minpoly
  2480. theta = self.primitive_element()
  2481. self._own_minpoly = minpoly(self.as_expr(theta), polys=True)
  2482. return self._own_minpoly
  2483. def to_root(self, radicals=True, minpoly=None):
  2484. """
  2485. Convert to an :py:class:`~.Expr` that is not an
  2486. :py:class:`~.AlgebraicNumber`, specifically, either a
  2487. :py:class:`~.ComplexRootOf`, or, optionally and where possible, an
  2488. expression in radicals.
  2489. Parameters
  2490. ==========
  2491. radicals : boolean, optional (default=True)
  2492. If ``True``, then we will try to return the root as an expression
  2493. in radicals. If that is not possible, we will return a
  2494. :py:class:`~.ComplexRootOf`.
  2495. minpoly : :py:class:`~.Poly`
  2496. If the minimal polynomial for `self` has been pre-computed, it can
  2497. be passed in order to save time.
  2498. """
  2499. if self.is_primitive_element and not isinstance(self.root, AlgebraicNumber):
  2500. return self.root
  2501. m = minpoly or self.minpoly_of_element()
  2502. roots = m.all_roots(radicals=radicals)
  2503. if len(roots) == 1:
  2504. return roots[0]
  2505. ex = self.as_expr()
  2506. for b in roots:
  2507. if m.same_root(b, ex):
  2508. return b
  2509. class RationalConstant(Rational):
  2510. """
  2511. Abstract base class for rationals with specific behaviors
  2512. Derived classes must define class attributes p and q and should probably all
  2513. be singletons.
  2514. """
  2515. __slots__ = ()
  2516. def __new__(cls):
  2517. return AtomicExpr.__new__(cls)
  2518. class IntegerConstant(Integer):
  2519. __slots__ = ()
  2520. def __new__(cls):
  2521. return AtomicExpr.__new__(cls)
  2522. class Zero(IntegerConstant, metaclass=Singleton):
  2523. """The number zero.
  2524. Zero is a singleton, and can be accessed by ``S.Zero``
  2525. Examples
  2526. ========
  2527. >>> from sympy import S, Integer
  2528. >>> Integer(0) is S.Zero
  2529. True
  2530. >>> 1/S.Zero
  2531. zoo
  2532. References
  2533. ==========
  2534. .. [1] https://en.wikipedia.org/wiki/Zero
  2535. """
  2536. p = 0
  2537. q = 1
  2538. is_positive = False
  2539. is_negative = False
  2540. is_zero = True
  2541. is_number = True
  2542. is_comparable = True
  2543. __slots__ = ()
  2544. def __getnewargs__(self):
  2545. return ()
  2546. @staticmethod
  2547. def __abs__():
  2548. return S.Zero
  2549. @staticmethod
  2550. def __neg__():
  2551. return S.Zero
  2552. def _eval_power(self, expt):
  2553. if expt.is_extended_positive:
  2554. return self
  2555. if expt.is_extended_negative:
  2556. return S.ComplexInfinity
  2557. if expt.is_extended_real is False:
  2558. return S.NaN
  2559. # infinities are already handled with pos and neg
  2560. # tests above; now throw away leading numbers on Mul
  2561. # exponent
  2562. coeff, terms = expt.as_coeff_Mul()
  2563. if coeff.is_negative:
  2564. return S.ComplexInfinity**terms
  2565. if coeff is not S.One: # there is a Number to discard
  2566. return self**terms
  2567. def _eval_order(self, *symbols):
  2568. # Order(0,x) -> 0
  2569. return self
  2570. def __bool__(self):
  2571. return False
  2572. class One(IntegerConstant, metaclass=Singleton):
  2573. """The number one.
  2574. One is a singleton, and can be accessed by ``S.One``.
  2575. Examples
  2576. ========
  2577. >>> from sympy import S, Integer
  2578. >>> Integer(1) is S.One
  2579. True
  2580. References
  2581. ==========
  2582. .. [1] https://en.wikipedia.org/wiki/1_%28number%29
  2583. """
  2584. is_number = True
  2585. is_positive = True
  2586. p = 1
  2587. q = 1
  2588. __slots__ = ()
  2589. def __getnewargs__(self):
  2590. return ()
  2591. @staticmethod
  2592. def __abs__():
  2593. return S.One
  2594. @staticmethod
  2595. def __neg__():
  2596. return S.NegativeOne
  2597. def _eval_power(self, expt):
  2598. return self
  2599. def _eval_order(self, *symbols):
  2600. return
  2601. @staticmethod
  2602. def factors(limit=None, use_trial=True, use_rho=False, use_pm1=False,
  2603. verbose=False, visual=False):
  2604. if visual:
  2605. return S.One
  2606. else:
  2607. return {}
  2608. class NegativeOne(IntegerConstant, metaclass=Singleton):
  2609. """The number negative one.
  2610. NegativeOne is a singleton, and can be accessed by ``S.NegativeOne``.
  2611. Examples
  2612. ========
  2613. >>> from sympy import S, Integer
  2614. >>> Integer(-1) is S.NegativeOne
  2615. True
  2616. See Also
  2617. ========
  2618. One
  2619. References
  2620. ==========
  2621. .. [1] https://en.wikipedia.org/wiki/%E2%88%921_%28number%29
  2622. """
  2623. is_number = True
  2624. p = -1
  2625. q = 1
  2626. __slots__ = ()
  2627. def __getnewargs__(self):
  2628. return ()
  2629. @staticmethod
  2630. def __abs__():
  2631. return S.One
  2632. @staticmethod
  2633. def __neg__():
  2634. return S.One
  2635. def _eval_power(self, expt):
  2636. if expt.is_odd:
  2637. return S.NegativeOne
  2638. if expt.is_even:
  2639. return S.One
  2640. if isinstance(expt, Number):
  2641. if isinstance(expt, Float):
  2642. return Float(-1.0)**expt
  2643. if expt is S.NaN:
  2644. return S.NaN
  2645. if expt in (S.Infinity, S.NegativeInfinity):
  2646. return S.NaN
  2647. if expt is S.Half:
  2648. return S.ImaginaryUnit
  2649. if isinstance(expt, Rational):
  2650. if expt.q == 2:
  2651. return S.ImaginaryUnit**Integer(expt.p)
  2652. i, r = divmod(expt.p, expt.q)
  2653. if i:
  2654. return self**i*self**Rational(r, expt.q)
  2655. return
  2656. class Half(RationalConstant, metaclass=Singleton):
  2657. """The rational number 1/2.
  2658. Half is a singleton, and can be accessed by ``S.Half``.
  2659. Examples
  2660. ========
  2661. >>> from sympy import S, Rational
  2662. >>> Rational(1, 2) is S.Half
  2663. True
  2664. References
  2665. ==========
  2666. .. [1] https://en.wikipedia.org/wiki/One_half
  2667. """
  2668. is_number = True
  2669. p = 1
  2670. q = 2
  2671. __slots__ = ()
  2672. def __getnewargs__(self):
  2673. return ()
  2674. @staticmethod
  2675. def __abs__():
  2676. return S.Half
  2677. class Infinity(Number, metaclass=Singleton):
  2678. r"""Positive infinite quantity.
  2679. Explanation
  2680. ===========
  2681. In real analysis the symbol `\infty` denotes an unbounded
  2682. limit: `x\to\infty` means that `x` grows without bound.
  2683. Infinity is often used not only to define a limit but as a value
  2684. in the affinely extended real number system. Points labeled `+\infty`
  2685. and `-\infty` can be added to the topological space of the real numbers,
  2686. producing the two-point compactification of the real numbers. Adding
  2687. algebraic properties to this gives us the extended real numbers.
  2688. Infinity is a singleton, and can be accessed by ``S.Infinity``,
  2689. or can be imported as ``oo``.
  2690. Examples
  2691. ========
  2692. >>> from sympy import oo, exp, limit, Symbol
  2693. >>> 1 + oo
  2694. oo
  2695. >>> 42/oo
  2696. 0
  2697. >>> x = Symbol('x')
  2698. >>> limit(exp(x), x, oo)
  2699. oo
  2700. See Also
  2701. ========
  2702. NegativeInfinity, NaN
  2703. References
  2704. ==========
  2705. .. [1] https://en.wikipedia.org/wiki/Infinity
  2706. """
  2707. is_commutative = True
  2708. is_number = True
  2709. is_complex = False
  2710. is_extended_real = True
  2711. is_infinite = True
  2712. is_comparable = True
  2713. is_extended_positive = True
  2714. is_prime = False
  2715. __slots__ = ()
  2716. def __new__(cls):
  2717. return AtomicExpr.__new__(cls)
  2718. def _latex(self, printer):
  2719. return r"\infty"
  2720. def _eval_subs(self, old, new):
  2721. if self == old:
  2722. return new
  2723. def _eval_evalf(self, prec=None):
  2724. return Float('inf')
  2725. def evalf(self, prec=None, **options):
  2726. return self._eval_evalf(prec)
  2727. @_sympifyit('other', NotImplemented)
  2728. def __add__(self, other):
  2729. if isinstance(other, Number) and global_parameters.evaluate:
  2730. if other in (S.NegativeInfinity, S.NaN):
  2731. return S.NaN
  2732. return self
  2733. return Number.__add__(self, other)
  2734. __radd__ = __add__
  2735. @_sympifyit('other', NotImplemented)
  2736. def __sub__(self, other):
  2737. if isinstance(other, Number) and global_parameters.evaluate:
  2738. if other in (S.Infinity, S.NaN):
  2739. return S.NaN
  2740. return self
  2741. return Number.__sub__(self, other)
  2742. @_sympifyit('other', NotImplemented)
  2743. def __rsub__(self, other):
  2744. return (-self).__add__(other)
  2745. @_sympifyit('other', NotImplemented)
  2746. def __mul__(self, other):
  2747. if isinstance(other, Number) and global_parameters.evaluate:
  2748. if other.is_zero or other is S.NaN:
  2749. return S.NaN
  2750. if other.is_extended_positive:
  2751. return self
  2752. return S.NegativeInfinity
  2753. return Number.__mul__(self, other)
  2754. __rmul__ = __mul__
  2755. @_sympifyit('other', NotImplemented)
  2756. def __truediv__(self, other):
  2757. if isinstance(other, Number) and global_parameters.evaluate:
  2758. if other is S.Infinity or \
  2759. other is S.NegativeInfinity or \
  2760. other is S.NaN:
  2761. return S.NaN
  2762. if other.is_extended_nonnegative:
  2763. return self
  2764. return S.NegativeInfinity
  2765. return Number.__truediv__(self, other)
  2766. def __abs__(self):
  2767. return S.Infinity
  2768. def __neg__(self):
  2769. return S.NegativeInfinity
  2770. def _eval_power(self, expt):
  2771. """
  2772. ``expt`` is symbolic object but not equal to 0 or 1.
  2773. ================ ======= ==============================
  2774. Expression Result Notes
  2775. ================ ======= ==============================
  2776. ``oo ** nan`` ``nan``
  2777. ``oo ** -p`` ``0`` ``p`` is number, ``oo``
  2778. ================ ======= ==============================
  2779. See Also
  2780. ========
  2781. Pow
  2782. NaN
  2783. NegativeInfinity
  2784. """
  2785. if expt.is_extended_positive:
  2786. return S.Infinity
  2787. if expt.is_extended_negative:
  2788. return S.Zero
  2789. if expt is S.NaN:
  2790. return S.NaN
  2791. if expt is S.ComplexInfinity:
  2792. return S.NaN
  2793. if expt.is_extended_real is False and expt.is_number:
  2794. from sympy.functions.elementary.complexes import re
  2795. expt_real = re(expt)
  2796. if expt_real.is_positive:
  2797. return S.ComplexInfinity
  2798. if expt_real.is_negative:
  2799. return S.Zero
  2800. if expt_real.is_zero:
  2801. return S.NaN
  2802. return self**expt.evalf()
  2803. def _as_mpf_val(self, prec):
  2804. return mlib.finf
  2805. def __hash__(self):
  2806. return super().__hash__()
  2807. def __eq__(self, other):
  2808. return other is S.Infinity or other == float('inf')
  2809. def __ne__(self, other):
  2810. return other is not S.Infinity and other != float('inf')
  2811. __gt__ = Expr.__gt__
  2812. __ge__ = Expr.__ge__
  2813. __lt__ = Expr.__lt__
  2814. __le__ = Expr.__le__
  2815. @_sympifyit('other', NotImplemented)
  2816. def __mod__(self, other):
  2817. if not isinstance(other, Expr):
  2818. return NotImplemented
  2819. return S.NaN
  2820. __rmod__ = __mod__
  2821. def floor(self):
  2822. return self
  2823. def ceiling(self):
  2824. return self
  2825. oo = S.Infinity
  2826. class NegativeInfinity(Number, metaclass=Singleton):
  2827. """Negative infinite quantity.
  2828. NegativeInfinity is a singleton, and can be accessed
  2829. by ``S.NegativeInfinity``.
  2830. See Also
  2831. ========
  2832. Infinity
  2833. """
  2834. is_extended_real = True
  2835. is_complex = False
  2836. is_commutative = True
  2837. is_infinite = True
  2838. is_comparable = True
  2839. is_extended_negative = True
  2840. is_number = True
  2841. is_prime = False
  2842. __slots__ = ()
  2843. def __new__(cls):
  2844. return AtomicExpr.__new__(cls)
  2845. def _latex(self, printer):
  2846. return r"-\infty"
  2847. def _eval_subs(self, old, new):
  2848. if self == old:
  2849. return new
  2850. def _eval_evalf(self, prec=None):
  2851. return Float('-inf')
  2852. def evalf(self, prec=None, **options):
  2853. return self._eval_evalf(prec)
  2854. @_sympifyit('other', NotImplemented)
  2855. def __add__(self, other):
  2856. if isinstance(other, Number) and global_parameters.evaluate:
  2857. if other in (S.Infinity, S.NaN):
  2858. return S.NaN
  2859. return self
  2860. return Number.__add__(self, other)
  2861. __radd__ = __add__
  2862. @_sympifyit('other', NotImplemented)
  2863. def __sub__(self, other):
  2864. if isinstance(other, Number) and global_parameters.evaluate:
  2865. if other in (S.NegativeInfinity, S.NaN):
  2866. return S.NaN
  2867. return self
  2868. return Number.__sub__(self, other)
  2869. @_sympifyit('other', NotImplemented)
  2870. def __rsub__(self, other):
  2871. return (-self).__add__(other)
  2872. @_sympifyit('other', NotImplemented)
  2873. def __mul__(self, other):
  2874. if isinstance(other, Number) and global_parameters.evaluate:
  2875. if other.is_zero or other is S.NaN:
  2876. return S.NaN
  2877. if other.is_extended_positive:
  2878. return self
  2879. return S.Infinity
  2880. return Number.__mul__(self, other)
  2881. __rmul__ = __mul__
  2882. @_sympifyit('other', NotImplemented)
  2883. def __truediv__(self, other):
  2884. if isinstance(other, Number) and global_parameters.evaluate:
  2885. if other is S.Infinity or \
  2886. other is S.NegativeInfinity or \
  2887. other is S.NaN:
  2888. return S.NaN
  2889. if other.is_extended_nonnegative:
  2890. return self
  2891. return S.Infinity
  2892. return Number.__truediv__(self, other)
  2893. def __abs__(self):
  2894. return S.Infinity
  2895. def __neg__(self):
  2896. return S.Infinity
  2897. def _eval_power(self, expt):
  2898. """
  2899. ``expt`` is symbolic object but not equal to 0 or 1.
  2900. ================ ======= ==============================
  2901. Expression Result Notes
  2902. ================ ======= ==============================
  2903. ``(-oo) ** nan`` ``nan``
  2904. ``(-oo) ** oo`` ``nan``
  2905. ``(-oo) ** -oo`` ``nan``
  2906. ``(-oo) ** e`` ``oo`` ``e`` is positive even integer
  2907. ``(-oo) ** o`` ``-oo`` ``o`` is positive odd integer
  2908. ================ ======= ==============================
  2909. See Also
  2910. ========
  2911. Infinity
  2912. Pow
  2913. NaN
  2914. """
  2915. if expt.is_number:
  2916. if expt is S.NaN or \
  2917. expt is S.Infinity or \
  2918. expt is S.NegativeInfinity:
  2919. return S.NaN
  2920. if isinstance(expt, Integer) and expt.is_extended_positive:
  2921. if expt.is_odd:
  2922. return S.NegativeInfinity
  2923. else:
  2924. return S.Infinity
  2925. inf_part = S.Infinity**expt
  2926. s_part = S.NegativeOne**expt
  2927. if inf_part == 0 and s_part.is_finite:
  2928. return inf_part
  2929. if (inf_part is S.ComplexInfinity and
  2930. s_part.is_finite and not s_part.is_zero):
  2931. return S.ComplexInfinity
  2932. return s_part*inf_part
  2933. def _as_mpf_val(self, prec):
  2934. return mlib.fninf
  2935. def __hash__(self):
  2936. return super().__hash__()
  2937. def __eq__(self, other):
  2938. return other is S.NegativeInfinity or other == float('-inf')
  2939. def __ne__(self, other):
  2940. return other is not S.NegativeInfinity and other != float('-inf')
  2941. __gt__ = Expr.__gt__
  2942. __ge__ = Expr.__ge__
  2943. __lt__ = Expr.__lt__
  2944. __le__ = Expr.__le__
  2945. @_sympifyit('other', NotImplemented)
  2946. def __mod__(self, other):
  2947. if not isinstance(other, Expr):
  2948. return NotImplemented
  2949. return S.NaN
  2950. __rmod__ = __mod__
  2951. def floor(self):
  2952. return self
  2953. def ceiling(self):
  2954. return self
  2955. def as_powers_dict(self):
  2956. return {S.NegativeOne: 1, S.Infinity: 1}
  2957. class NaN(Number, metaclass=Singleton):
  2958. """
  2959. Not a Number.
  2960. Explanation
  2961. ===========
  2962. This serves as a place holder for numeric values that are indeterminate.
  2963. Most operations on NaN, produce another NaN. Most indeterminate forms,
  2964. such as ``0/0`` or ``oo - oo` produce NaN. Two exceptions are ``0**0``
  2965. and ``oo**0``, which all produce ``1`` (this is consistent with Python's
  2966. float).
  2967. NaN is loosely related to floating point nan, which is defined in the
  2968. IEEE 754 floating point standard, and corresponds to the Python
  2969. ``float('nan')``. Differences are noted below.
  2970. NaN is mathematically not equal to anything else, even NaN itself. This
  2971. explains the initially counter-intuitive results with ``Eq`` and ``==`` in
  2972. the examples below.
  2973. NaN is not comparable so inequalities raise a TypeError. This is in
  2974. contrast with floating point nan where all inequalities are false.
  2975. NaN is a singleton, and can be accessed by ``S.NaN``, or can be imported
  2976. as ``nan``.
  2977. Examples
  2978. ========
  2979. >>> from sympy import nan, S, oo, Eq
  2980. >>> nan is S.NaN
  2981. True
  2982. >>> oo - oo
  2983. nan
  2984. >>> nan + 1
  2985. nan
  2986. >>> Eq(nan, nan) # mathematical equality
  2987. False
  2988. >>> nan == nan # structural equality
  2989. True
  2990. References
  2991. ==========
  2992. .. [1] https://en.wikipedia.org/wiki/NaN
  2993. """
  2994. is_commutative = True
  2995. is_extended_real = None
  2996. is_real = None
  2997. is_rational = None
  2998. is_algebraic = None
  2999. is_transcendental = None
  3000. is_integer = None
  3001. is_comparable = False
  3002. is_finite = None
  3003. is_zero = None
  3004. is_prime = None
  3005. is_positive = None
  3006. is_negative = None
  3007. is_number = True
  3008. __slots__ = ()
  3009. def __new__(cls):
  3010. return AtomicExpr.__new__(cls)
  3011. def _latex(self, printer):
  3012. return r"\text{NaN}"
  3013. def __neg__(self):
  3014. return self
  3015. @_sympifyit('other', NotImplemented)
  3016. def __add__(self, other):
  3017. return self
  3018. @_sympifyit('other', NotImplemented)
  3019. def __sub__(self, other):
  3020. return self
  3021. @_sympifyit('other', NotImplemented)
  3022. def __mul__(self, other):
  3023. return self
  3024. @_sympifyit('other', NotImplemented)
  3025. def __truediv__(self, other):
  3026. return self
  3027. def floor(self):
  3028. return self
  3029. def ceiling(self):
  3030. return self
  3031. def _as_mpf_val(self, prec):
  3032. return _mpf_nan
  3033. def __hash__(self):
  3034. return super().__hash__()
  3035. def __eq__(self, other):
  3036. # NaN is structurally equal to another NaN
  3037. return other is S.NaN
  3038. def __ne__(self, other):
  3039. return other is not S.NaN
  3040. # Expr will _sympify and raise TypeError
  3041. __gt__ = Expr.__gt__
  3042. __ge__ = Expr.__ge__
  3043. __lt__ = Expr.__lt__
  3044. __le__ = Expr.__le__
  3045. nan = S.NaN
  3046. @dispatch(NaN, Expr) # type:ignore
  3047. def _eval_is_eq(a, b): # noqa:F811
  3048. return False
  3049. class ComplexInfinity(AtomicExpr, metaclass=Singleton):
  3050. r"""Complex infinity.
  3051. Explanation
  3052. ===========
  3053. In complex analysis the symbol `\tilde\infty`, called "complex
  3054. infinity", represents a quantity with infinite magnitude, but
  3055. undetermined complex phase.
  3056. ComplexInfinity is a singleton, and can be accessed by
  3057. ``S.ComplexInfinity``, or can be imported as ``zoo``.
  3058. Examples
  3059. ========
  3060. >>> from sympy import zoo
  3061. >>> zoo + 42
  3062. zoo
  3063. >>> 42/zoo
  3064. 0
  3065. >>> zoo + zoo
  3066. nan
  3067. >>> zoo*zoo
  3068. zoo
  3069. See Also
  3070. ========
  3071. Infinity
  3072. """
  3073. is_commutative = True
  3074. is_infinite = True
  3075. is_number = True
  3076. is_prime = False
  3077. is_complex = False
  3078. is_extended_real = False
  3079. kind = NumberKind
  3080. __slots__ = ()
  3081. def __new__(cls):
  3082. return AtomicExpr.__new__(cls)
  3083. def _latex(self, printer):
  3084. return r"\tilde{\infty}"
  3085. @staticmethod
  3086. def __abs__():
  3087. return S.Infinity
  3088. def floor(self):
  3089. return self
  3090. def ceiling(self):
  3091. return self
  3092. @staticmethod
  3093. def __neg__():
  3094. return S.ComplexInfinity
  3095. def _eval_power(self, expt):
  3096. if expt is S.ComplexInfinity:
  3097. return S.NaN
  3098. if isinstance(expt, Number):
  3099. if expt.is_zero:
  3100. return S.NaN
  3101. else:
  3102. if expt.is_positive:
  3103. return S.ComplexInfinity
  3104. else:
  3105. return S.Zero
  3106. zoo = S.ComplexInfinity
  3107. class NumberSymbol(AtomicExpr):
  3108. is_commutative = True
  3109. is_finite = True
  3110. is_number = True
  3111. __slots__ = ()
  3112. is_NumberSymbol = True
  3113. kind = NumberKind
  3114. def __new__(cls):
  3115. return AtomicExpr.__new__(cls)
  3116. def approximation(self, number_cls):
  3117. """ Return an interval with number_cls endpoints
  3118. that contains the value of NumberSymbol.
  3119. If not implemented, then return None.
  3120. """
  3121. def _eval_evalf(self, prec):
  3122. return Float._new(self._as_mpf_val(prec), prec)
  3123. def __eq__(self, other):
  3124. try:
  3125. other = _sympify(other)
  3126. except SympifyError:
  3127. return NotImplemented
  3128. if self is other:
  3129. return True
  3130. if other.is_Number and self.is_irrational:
  3131. return False
  3132. return False # NumberSymbol != non-(Number|self)
  3133. def __ne__(self, other):
  3134. return not self == other
  3135. def __le__(self, other):
  3136. if self is other:
  3137. return S.true
  3138. return Expr.__le__(self, other)
  3139. def __ge__(self, other):
  3140. if self is other:
  3141. return S.true
  3142. return Expr.__ge__(self, other)
  3143. def __int__(self):
  3144. # subclass with appropriate return value
  3145. raise NotImplementedError
  3146. def __hash__(self):
  3147. return super().__hash__()
  3148. class Exp1(NumberSymbol, metaclass=Singleton):
  3149. r"""The `e` constant.
  3150. Explanation
  3151. ===========
  3152. The transcendental number `e = 2.718281828\ldots` is the base of the
  3153. natural logarithm and of the exponential function, `e = \exp(1)`.
  3154. Sometimes called Euler's number or Napier's constant.
  3155. Exp1 is a singleton, and can be accessed by ``S.Exp1``,
  3156. or can be imported as ``E``.
  3157. Examples
  3158. ========
  3159. >>> from sympy import exp, log, E
  3160. >>> E is exp(1)
  3161. True
  3162. >>> log(E)
  3163. 1
  3164. References
  3165. ==========
  3166. .. [1] https://en.wikipedia.org/wiki/E_%28mathematical_constant%29
  3167. """
  3168. is_real = True
  3169. is_positive = True
  3170. is_negative = False # XXX Forces is_negative/is_nonnegative
  3171. is_irrational = True
  3172. is_number = True
  3173. is_algebraic = False
  3174. is_transcendental = True
  3175. __slots__ = ()
  3176. def _latex(self, printer):
  3177. return r"e"
  3178. @staticmethod
  3179. def __abs__():
  3180. return S.Exp1
  3181. def __int__(self):
  3182. return 2
  3183. def _as_mpf_val(self, prec):
  3184. return mpf_e(prec)
  3185. def approximation_interval(self, number_cls):
  3186. if issubclass(number_cls, Integer):
  3187. return (Integer(2), Integer(3))
  3188. elif issubclass(number_cls, Rational):
  3189. pass
  3190. def _eval_power(self, expt):
  3191. if global_parameters.exp_is_pow:
  3192. return self._eval_power_exp_is_pow(expt)
  3193. else:
  3194. from sympy.functions.elementary.exponential import exp
  3195. return exp(expt)
  3196. def _eval_power_exp_is_pow(self, arg):
  3197. if arg.is_Number:
  3198. if arg is oo:
  3199. return oo
  3200. elif arg == -oo:
  3201. return S.Zero
  3202. from sympy.functions.elementary.exponential import log
  3203. if isinstance(arg, log):
  3204. return arg.args[0]
  3205. # don't autoexpand Pow or Mul (see the issue 3351):
  3206. elif not arg.is_Add:
  3207. Ioo = I*oo
  3208. if arg in [Ioo, -Ioo]:
  3209. return nan
  3210. coeff = arg.coeff(pi*I)
  3211. if coeff:
  3212. if (2*coeff).is_integer:
  3213. if coeff.is_even:
  3214. return S.One
  3215. elif coeff.is_odd:
  3216. return S.NegativeOne
  3217. elif (coeff + S.Half).is_even:
  3218. return -I
  3219. elif (coeff + S.Half).is_odd:
  3220. return I
  3221. elif coeff.is_Rational:
  3222. ncoeff = coeff % 2 # restrict to [0, 2pi)
  3223. if ncoeff > 1: # restrict to (-pi, pi]
  3224. ncoeff -= 2
  3225. if ncoeff != coeff:
  3226. return S.Exp1**(ncoeff*S.Pi*S.ImaginaryUnit)
  3227. # Warning: code in risch.py will be very sensitive to changes
  3228. # in this (see DifferentialExtension).
  3229. # look for a single log factor
  3230. coeff, terms = arg.as_coeff_Mul()
  3231. # but it can't be multiplied by oo
  3232. if coeff in (oo, -oo):
  3233. return
  3234. coeffs, log_term = [coeff], None
  3235. for term in Mul.make_args(terms):
  3236. if isinstance(term, log):
  3237. if log_term is None:
  3238. log_term = term.args[0]
  3239. else:
  3240. return
  3241. elif term.is_comparable:
  3242. coeffs.append(term)
  3243. else:
  3244. return
  3245. return log_term**Mul(*coeffs) if log_term else None
  3246. elif arg.is_Add:
  3247. out = []
  3248. add = []
  3249. argchanged = False
  3250. for a in arg.args:
  3251. if a is S.One:
  3252. add.append(a)
  3253. continue
  3254. newa = self**a
  3255. if isinstance(newa, Pow) and newa.base is self:
  3256. if newa.exp != a:
  3257. add.append(newa.exp)
  3258. argchanged = True
  3259. else:
  3260. add.append(a)
  3261. else:
  3262. out.append(newa)
  3263. if out or argchanged:
  3264. return Mul(*out)*Pow(self, Add(*add), evaluate=False)
  3265. elif arg.is_Matrix:
  3266. return arg.exp()
  3267. def _eval_rewrite_as_sin(self, **kwargs):
  3268. from sympy.functions.elementary.trigonometric import sin
  3269. return sin(I + S.Pi/2) - I*sin(I)
  3270. def _eval_rewrite_as_cos(self, **kwargs):
  3271. from sympy.functions.elementary.trigonometric import cos
  3272. return cos(I) + I*cos(I + S.Pi/2)
  3273. E = S.Exp1
  3274. class Pi(NumberSymbol, metaclass=Singleton):
  3275. r"""The `\pi` constant.
  3276. Explanation
  3277. ===========
  3278. The transcendental number `\pi = 3.141592654\ldots` represents the ratio
  3279. of a circle's circumference to its diameter, the area of the unit circle,
  3280. the half-period of trigonometric functions, and many other things
  3281. in mathematics.
  3282. Pi is a singleton, and can be accessed by ``S.Pi``, or can
  3283. be imported as ``pi``.
  3284. Examples
  3285. ========
  3286. >>> from sympy import S, pi, oo, sin, exp, integrate, Symbol
  3287. >>> S.Pi
  3288. pi
  3289. >>> pi > 3
  3290. True
  3291. >>> pi.is_irrational
  3292. True
  3293. >>> x = Symbol('x')
  3294. >>> sin(x + 2*pi)
  3295. sin(x)
  3296. >>> integrate(exp(-x**2), (x, -oo, oo))
  3297. sqrt(pi)
  3298. References
  3299. ==========
  3300. .. [1] https://en.wikipedia.org/wiki/Pi
  3301. """
  3302. is_real = True
  3303. is_positive = True
  3304. is_negative = False
  3305. is_irrational = True
  3306. is_number = True
  3307. is_algebraic = False
  3308. is_transcendental = True
  3309. __slots__ = ()
  3310. def _latex(self, printer):
  3311. return r"\pi"
  3312. @staticmethod
  3313. def __abs__():
  3314. return S.Pi
  3315. def __int__(self):
  3316. return 3
  3317. def _as_mpf_val(self, prec):
  3318. return mpf_pi(prec)
  3319. def approximation_interval(self, number_cls):
  3320. if issubclass(number_cls, Integer):
  3321. return (Integer(3), Integer(4))
  3322. elif issubclass(number_cls, Rational):
  3323. return (Rational(223, 71, 1), Rational(22, 7, 1))
  3324. pi = S.Pi
  3325. class GoldenRatio(NumberSymbol, metaclass=Singleton):
  3326. r"""The golden ratio, `\phi`.
  3327. Explanation
  3328. ===========
  3329. `\phi = \frac{1 + \sqrt{5}}{2}` is algebraic number. Two quantities
  3330. are in the golden ratio if their ratio is the same as the ratio of
  3331. their sum to the larger of the two quantities, i.e. their maximum.
  3332. GoldenRatio is a singleton, and can be accessed by ``S.GoldenRatio``.
  3333. Examples
  3334. ========
  3335. >>> from sympy import S
  3336. >>> S.GoldenRatio > 1
  3337. True
  3338. >>> S.GoldenRatio.expand(func=True)
  3339. 1/2 + sqrt(5)/2
  3340. >>> S.GoldenRatio.is_irrational
  3341. True
  3342. References
  3343. ==========
  3344. .. [1] https://en.wikipedia.org/wiki/Golden_ratio
  3345. """
  3346. is_real = True
  3347. is_positive = True
  3348. is_negative = False
  3349. is_irrational = True
  3350. is_number = True
  3351. is_algebraic = True
  3352. is_transcendental = False
  3353. __slots__ = ()
  3354. def _latex(self, printer):
  3355. return r"\phi"
  3356. def __int__(self):
  3357. return 1
  3358. def _as_mpf_val(self, prec):
  3359. # XXX track down why this has to be increased
  3360. rv = mlib.from_man_exp(phi_fixed(prec + 10), -prec - 10)
  3361. return mpf_norm(rv, prec)
  3362. def _eval_expand_func(self, **hints):
  3363. from sympy.functions.elementary.miscellaneous import sqrt
  3364. return S.Half + S.Half*sqrt(5)
  3365. def approximation_interval(self, number_cls):
  3366. if issubclass(number_cls, Integer):
  3367. return (S.One, Rational(2))
  3368. elif issubclass(number_cls, Rational):
  3369. pass
  3370. _eval_rewrite_as_sqrt = _eval_expand_func
  3371. class TribonacciConstant(NumberSymbol, metaclass=Singleton):
  3372. r"""The tribonacci constant.
  3373. Explanation
  3374. ===========
  3375. The tribonacci numbers are like the Fibonacci numbers, but instead
  3376. of starting with two predetermined terms, the sequence starts with
  3377. three predetermined terms and each term afterwards is the sum of the
  3378. preceding three terms.
  3379. The tribonacci constant is the ratio toward which adjacent tribonacci
  3380. numbers tend. It is a root of the polynomial `x^3 - x^2 - x - 1 = 0`,
  3381. and also satisfies the equation `x + x^{-3} = 2`.
  3382. TribonacciConstant is a singleton, and can be accessed
  3383. by ``S.TribonacciConstant``.
  3384. Examples
  3385. ========
  3386. >>> from sympy import S
  3387. >>> S.TribonacciConstant > 1
  3388. True
  3389. >>> S.TribonacciConstant.expand(func=True)
  3390. 1/3 + (19 - 3*sqrt(33))**(1/3)/3 + (3*sqrt(33) + 19)**(1/3)/3
  3391. >>> S.TribonacciConstant.is_irrational
  3392. True
  3393. >>> S.TribonacciConstant.n(20)
  3394. 1.8392867552141611326
  3395. References
  3396. ==========
  3397. .. [1] https://en.wikipedia.org/wiki/Generalizations_of_Fibonacci_numbers#Tribonacci_numbers
  3398. """
  3399. is_real = True
  3400. is_positive = True
  3401. is_negative = False
  3402. is_irrational = True
  3403. is_number = True
  3404. is_algebraic = True
  3405. is_transcendental = False
  3406. __slots__ = ()
  3407. def _latex(self, printer):
  3408. return r"\text{TribonacciConstant}"
  3409. def __int__(self):
  3410. return 1
  3411. def _eval_evalf(self, prec):
  3412. rv = self._eval_expand_func(function=True)._eval_evalf(prec + 4)
  3413. return Float(rv, precision=prec)
  3414. def _eval_expand_func(self, **hints):
  3415. from sympy.functions.elementary.miscellaneous import cbrt, sqrt
  3416. return (1 + cbrt(19 - 3*sqrt(33)) + cbrt(19 + 3*sqrt(33))) / 3
  3417. def approximation_interval(self, number_cls):
  3418. if issubclass(number_cls, Integer):
  3419. return (S.One, Rational(2))
  3420. elif issubclass(number_cls, Rational):
  3421. pass
  3422. _eval_rewrite_as_sqrt = _eval_expand_func
  3423. class EulerGamma(NumberSymbol, metaclass=Singleton):
  3424. r"""The Euler-Mascheroni constant.
  3425. Explanation
  3426. ===========
  3427. `\gamma = 0.5772157\ldots` (also called Euler's constant) is a mathematical
  3428. constant recurring in analysis and number theory. It is defined as the
  3429. limiting difference between the harmonic series and the
  3430. natural logarithm:
  3431. .. math:: \gamma = \lim\limits_{n\to\infty}
  3432. \left(\sum\limits_{k=1}^n\frac{1}{k} - \ln n\right)
  3433. EulerGamma is a singleton, and can be accessed by ``S.EulerGamma``.
  3434. Examples
  3435. ========
  3436. >>> from sympy import S
  3437. >>> S.EulerGamma.is_irrational
  3438. >>> S.EulerGamma > 0
  3439. True
  3440. >>> S.EulerGamma > 1
  3441. False
  3442. References
  3443. ==========
  3444. .. [1] https://en.wikipedia.org/wiki/Euler%E2%80%93Mascheroni_constant
  3445. """
  3446. is_real = True
  3447. is_positive = True
  3448. is_negative = False
  3449. is_irrational = None
  3450. is_number = True
  3451. __slots__ = ()
  3452. def _latex(self, printer):
  3453. return r"\gamma"
  3454. def __int__(self):
  3455. return 0
  3456. def _as_mpf_val(self, prec):
  3457. # XXX track down why this has to be increased
  3458. v = mlib.libhyper.euler_fixed(prec + 10)
  3459. rv = mlib.from_man_exp(v, -prec - 10)
  3460. return mpf_norm(rv, prec)
  3461. def approximation_interval(self, number_cls):
  3462. if issubclass(number_cls, Integer):
  3463. return (S.Zero, S.One)
  3464. elif issubclass(number_cls, Rational):
  3465. return (S.Half, Rational(3, 5, 1))
  3466. class Catalan(NumberSymbol, metaclass=Singleton):
  3467. r"""Catalan's constant.
  3468. Explanation
  3469. ===========
  3470. $G = 0.91596559\ldots$ is given by the infinite series
  3471. .. math:: G = \sum_{k=0}^{\infty} \frac{(-1)^k}{(2k+1)^2}
  3472. Catalan is a singleton, and can be accessed by ``S.Catalan``.
  3473. Examples
  3474. ========
  3475. >>> from sympy import S
  3476. >>> S.Catalan.is_irrational
  3477. >>> S.Catalan > 0
  3478. True
  3479. >>> S.Catalan > 1
  3480. False
  3481. References
  3482. ==========
  3483. .. [1] https://en.wikipedia.org/wiki/Catalan%27s_constant
  3484. """
  3485. is_real = True
  3486. is_positive = True
  3487. is_negative = False
  3488. is_irrational = None
  3489. is_number = True
  3490. __slots__ = ()
  3491. def __int__(self):
  3492. return 0
  3493. def _as_mpf_val(self, prec):
  3494. # XXX track down why this has to be increased
  3495. v = mlib.catalan_fixed(prec + 10)
  3496. rv = mlib.from_man_exp(v, -prec - 10)
  3497. return mpf_norm(rv, prec)
  3498. def approximation_interval(self, number_cls):
  3499. if issubclass(number_cls, Integer):
  3500. return (S.Zero, S.One)
  3501. elif issubclass(number_cls, Rational):
  3502. return (Rational(9, 10, 1), S.One)
  3503. def _eval_rewrite_as_Sum(self, k_sym=None, symbols=None):
  3504. if (k_sym is not None) or (symbols is not None):
  3505. return self
  3506. from .symbol import Dummy
  3507. from sympy.concrete.summations import Sum
  3508. k = Dummy('k', integer=True, nonnegative=True)
  3509. return Sum(S.NegativeOne**k / (2*k+1)**2, (k, 0, S.Infinity))
  3510. def _latex(self, printer):
  3511. return "G"
  3512. class ImaginaryUnit(AtomicExpr, metaclass=Singleton):
  3513. r"""The imaginary unit, `i = \sqrt{-1}`.
  3514. I is a singleton, and can be accessed by ``S.I``, or can be
  3515. imported as ``I``.
  3516. Examples
  3517. ========
  3518. >>> from sympy import I, sqrt
  3519. >>> sqrt(-1)
  3520. I
  3521. >>> I*I
  3522. -1
  3523. >>> 1/I
  3524. -I
  3525. References
  3526. ==========
  3527. .. [1] https://en.wikipedia.org/wiki/Imaginary_unit
  3528. """
  3529. is_commutative = True
  3530. is_imaginary = True
  3531. is_finite = True
  3532. is_number = True
  3533. is_algebraic = True
  3534. is_transcendental = False
  3535. kind = NumberKind
  3536. __slots__ = ()
  3537. def _latex(self, printer):
  3538. return printer._settings['imaginary_unit_latex']
  3539. @staticmethod
  3540. def __abs__():
  3541. return S.One
  3542. def _eval_evalf(self, prec):
  3543. return self
  3544. def _eval_conjugate(self):
  3545. return -S.ImaginaryUnit
  3546. def _eval_power(self, expt):
  3547. """
  3548. b is I = sqrt(-1)
  3549. e is symbolic object but not equal to 0, 1
  3550. I**r -> (-1)**(r/2) -> exp(r/2*Pi*I) -> sin(Pi*r/2) + cos(Pi*r/2)*I, r is decimal
  3551. I**0 mod 4 -> 1
  3552. I**1 mod 4 -> I
  3553. I**2 mod 4 -> -1
  3554. I**3 mod 4 -> -I
  3555. """
  3556. if isinstance(expt, Integer):
  3557. expt = expt % 4
  3558. if expt == 0:
  3559. return S.One
  3560. elif expt == 1:
  3561. return S.ImaginaryUnit
  3562. elif expt == 2:
  3563. return S.NegativeOne
  3564. elif expt == 3:
  3565. return -S.ImaginaryUnit
  3566. if isinstance(expt, Rational):
  3567. i, r = divmod(expt, 2)
  3568. rv = Pow(S.ImaginaryUnit, r, evaluate=False)
  3569. if i % 2:
  3570. return Mul(S.NegativeOne, rv, evaluate=False)
  3571. return rv
  3572. def as_base_exp(self):
  3573. return S.NegativeOne, S.Half
  3574. @property
  3575. def _mpc_(self):
  3576. return (Float(0)._mpf_, Float(1)._mpf_)
  3577. I = S.ImaginaryUnit
  3578. @dispatch(Tuple, Number) # type:ignore
  3579. def _eval_is_eq(self, other): # noqa: F811
  3580. return False
  3581. def sympify_fractions(f):
  3582. return Rational(f.numerator, f.denominator, 1)
  3583. _sympy_converter[fractions.Fraction] = sympify_fractions
  3584. if HAS_GMPY:
  3585. def sympify_mpz(x):
  3586. return Integer(int(x))
  3587. # XXX: The sympify_mpq function here was never used because it is
  3588. # overridden by the other sympify_mpq function below. Maybe it should just
  3589. # be removed or maybe it should be used for something...
  3590. def sympify_mpq(x):
  3591. return Rational(int(x.numerator), int(x.denominator))
  3592. _sympy_converter[type(gmpy.mpz(1))] = sympify_mpz
  3593. _sympy_converter[type(gmpy.mpq(1, 2))] = sympify_mpq
  3594. def sympify_mpmath_mpq(x):
  3595. p, q = x._mpq_
  3596. return Rational(p, q, 1)
  3597. _sympy_converter[type(mpmath.rational.mpq(1, 2))] = sympify_mpmath_mpq
  3598. def sympify_mpmath(x):
  3599. return Expr._from_mpmath(x, x.context.prec)
  3600. _sympy_converter[mpnumeric] = sympify_mpmath
  3601. def sympify_complex(a):
  3602. real, imag = list(map(sympify, (a.real, a.imag)))
  3603. return real + S.ImaginaryUnit*imag
  3604. _sympy_converter[complex] = sympify_complex
  3605. from .power import Pow, integer_nthroot
  3606. from .mul import Mul
  3607. Mul.identity = One()
  3608. from .add import Add
  3609. Add.identity = Zero()
  3610. def _register_classes():
  3611. numbers.Number.register(Number)
  3612. numbers.Real.register(Float)
  3613. numbers.Rational.register(Rational)
  3614. numbers.Integral.register(Integer)
  3615. _register_classes()