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.

1967 lines
73 KiB

6 months ago
  1. from typing import Callable, Tuple as tTuple
  2. from math import log as _log, sqrt as _sqrt
  3. from itertools import product
  4. from .sympify import _sympify
  5. from .cache import cacheit
  6. from .singleton import S
  7. from .expr import Expr
  8. from .evalf import PrecisionExhausted
  9. from .function import (expand_complex, expand_multinomial,
  10. expand_mul, _mexpand, PoleError)
  11. from .logic import fuzzy_bool, fuzzy_not, fuzzy_and, fuzzy_or
  12. from .parameters import global_parameters
  13. from .relational import is_gt, is_lt
  14. from .kind import NumberKind, UndefinedKind
  15. from sympy.external.gmpy import HAS_GMPY, gmpy
  16. from sympy.utilities.iterables import sift
  17. from sympy.utilities.exceptions import sympy_deprecation_warning
  18. from sympy.utilities.misc import as_int
  19. from sympy.multipledispatch import Dispatcher
  20. from mpmath.libmp import sqrtrem as mpmath_sqrtrem
  21. def isqrt(n):
  22. """Return the largest integer less than or equal to sqrt(n)."""
  23. if n < 0:
  24. raise ValueError("n must be nonnegative")
  25. n = int(n)
  26. # Fast path: with IEEE 754 binary64 floats and a correctly-rounded
  27. # math.sqrt, int(math.sqrt(n)) works for any integer n satisfying 0 <= n <
  28. # 4503599761588224 = 2**52 + 2**27. But Python doesn't guarantee either
  29. # IEEE 754 format floats *or* correct rounding of math.sqrt, so check the
  30. # answer and fall back to the slow method if necessary.
  31. if n < 4503599761588224:
  32. s = int(_sqrt(n))
  33. if 0 <= n - s*s <= 2*s:
  34. return s
  35. return integer_nthroot(n, 2)[0]
  36. def integer_nthroot(y, n):
  37. """
  38. Return a tuple containing x = floor(y**(1/n))
  39. and a boolean indicating whether the result is exact (that is,
  40. whether x**n == y).
  41. Examples
  42. ========
  43. >>> from sympy import integer_nthroot
  44. >>> integer_nthroot(16, 2)
  45. (4, True)
  46. >>> integer_nthroot(26, 2)
  47. (5, False)
  48. To simply determine if a number is a perfect square, the is_square
  49. function should be used:
  50. >>> from sympy.ntheory.primetest import is_square
  51. >>> is_square(26)
  52. False
  53. See Also
  54. ========
  55. sympy.ntheory.primetest.is_square
  56. integer_log
  57. """
  58. y, n = as_int(y), as_int(n)
  59. if y < 0:
  60. raise ValueError("y must be nonnegative")
  61. if n < 1:
  62. raise ValueError("n must be positive")
  63. if HAS_GMPY and n < 2**63:
  64. # Currently it works only for n < 2**63, else it produces TypeError
  65. # sympy issue: https://github.com/sympy/sympy/issues/18374
  66. # gmpy2 issue: https://github.com/aleaxit/gmpy/issues/257
  67. if HAS_GMPY >= 2:
  68. x, t = gmpy.iroot(y, n)
  69. else:
  70. x, t = gmpy.root(y, n)
  71. return as_int(x), bool(t)
  72. return _integer_nthroot_python(y, n)
  73. def _integer_nthroot_python(y, n):
  74. if y in (0, 1):
  75. return y, True
  76. if n == 1:
  77. return y, True
  78. if n == 2:
  79. x, rem = mpmath_sqrtrem(y)
  80. return int(x), not rem
  81. if n > y:
  82. return 1, False
  83. # Get initial estimate for Newton's method. Care must be taken to
  84. # avoid overflow
  85. try:
  86. guess = int(y**(1./n) + 0.5)
  87. except OverflowError:
  88. exp = _log(y, 2)/n
  89. if exp > 53:
  90. shift = int(exp - 53)
  91. guess = int(2.0**(exp - shift) + 1) << shift
  92. else:
  93. guess = int(2.0**exp)
  94. if guess > 2**50:
  95. # Newton iteration
  96. xprev, x = -1, guess
  97. while 1:
  98. t = x**(n - 1)
  99. xprev, x = x, ((n - 1)*x + y//t)//n
  100. if abs(x - xprev) < 2:
  101. break
  102. else:
  103. x = guess
  104. # Compensate
  105. t = x**n
  106. while t < y:
  107. x += 1
  108. t = x**n
  109. while t > y:
  110. x -= 1
  111. t = x**n
  112. return int(x), t == y # int converts long to int if possible
  113. def integer_log(y, x):
  114. r"""
  115. Returns ``(e, bool)`` where e is the largest nonnegative integer
  116. such that :math:`|y| \geq |x^e|` and ``bool`` is True if $y = x^e$.
  117. Examples
  118. ========
  119. >>> from sympy import integer_log
  120. >>> integer_log(125, 5)
  121. (3, True)
  122. >>> integer_log(17, 9)
  123. (1, False)
  124. >>> integer_log(4, -2)
  125. (2, True)
  126. >>> integer_log(-125,-5)
  127. (3, True)
  128. See Also
  129. ========
  130. integer_nthroot
  131. sympy.ntheory.primetest.is_square
  132. sympy.ntheory.factor_.multiplicity
  133. sympy.ntheory.factor_.perfect_power
  134. """
  135. if x == 1:
  136. raise ValueError('x cannot take value as 1')
  137. if y == 0:
  138. raise ValueError('y cannot take value as 0')
  139. if x in (-2, 2):
  140. x = int(x)
  141. y = as_int(y)
  142. e = y.bit_length() - 1
  143. return e, x**e == y
  144. if x < 0:
  145. n, b = integer_log(y if y > 0 else -y, -x)
  146. return n, b and bool(n % 2 if y < 0 else not n % 2)
  147. x = as_int(x)
  148. y = as_int(y)
  149. r = e = 0
  150. while y >= x:
  151. d = x
  152. m = 1
  153. while y >= d:
  154. y, rem = divmod(y, d)
  155. r = r or rem
  156. e += m
  157. if y > d:
  158. d *= d
  159. m *= 2
  160. return e, r == 0 and y == 1
  161. class Pow(Expr):
  162. """
  163. Defines the expression x**y as "x raised to a power y"
  164. .. deprecated:: 1.7
  165. Using arguments that aren't subclasses of :class:`~.Expr` in core
  166. operators (:class:`~.Mul`, :class:`~.Add`, and :class:`~.Pow`) is
  167. deprecated. See :ref:`non-expr-args-deprecated` for details.
  168. Singleton definitions involving (0, 1, -1, oo, -oo, I, -I):
  169. +--------------+---------+-----------------------------------------------+
  170. | expr | value | reason |
  171. +==============+=========+===============================================+
  172. | z**0 | 1 | Although arguments over 0**0 exist, see [2]. |
  173. +--------------+---------+-----------------------------------------------+
  174. | z**1 | z | |
  175. +--------------+---------+-----------------------------------------------+
  176. | (-oo)**(-1) | 0 | |
  177. +--------------+---------+-----------------------------------------------+
  178. | (-1)**-1 | -1 | |
  179. +--------------+---------+-----------------------------------------------+
  180. | S.Zero**-1 | zoo | This is not strictly true, as 0**-1 may be |
  181. | | | undefined, but is convenient in some contexts |
  182. | | | where the base is assumed to be positive. |
  183. +--------------+---------+-----------------------------------------------+
  184. | 1**-1 | 1 | |
  185. +--------------+---------+-----------------------------------------------+
  186. | oo**-1 | 0 | |
  187. +--------------+---------+-----------------------------------------------+
  188. | 0**oo | 0 | Because for all complex numbers z near |
  189. | | | 0, z**oo -> 0. |
  190. +--------------+---------+-----------------------------------------------+
  191. | 0**-oo | zoo | This is not strictly true, as 0**oo may be |
  192. | | | oscillating between positive and negative |
  193. | | | values or rotating in the complex plane. |
  194. | | | It is convenient, however, when the base |
  195. | | | is positive. |
  196. +--------------+---------+-----------------------------------------------+
  197. | 1**oo | nan | Because there are various cases where |
  198. | 1**-oo | | lim(x(t),t)=1, lim(y(t),t)=oo (or -oo), |
  199. | | | but lim( x(t)**y(t), t) != 1. See [3]. |
  200. +--------------+---------+-----------------------------------------------+
  201. | b**zoo | nan | Because b**z has no limit as z -> zoo |
  202. +--------------+---------+-----------------------------------------------+
  203. | (-1)**oo | nan | Because of oscillations in the limit. |
  204. | (-1)**(-oo) | | |
  205. +--------------+---------+-----------------------------------------------+
  206. | oo**oo | oo | |
  207. +--------------+---------+-----------------------------------------------+
  208. | oo**-oo | 0 | |
  209. +--------------+---------+-----------------------------------------------+
  210. | (-oo)**oo | nan | |
  211. | (-oo)**-oo | | |
  212. +--------------+---------+-----------------------------------------------+
  213. | oo**I | nan | oo**e could probably be best thought of as |
  214. | (-oo)**I | | the limit of x**e for real x as x tends to |
  215. | | | oo. If e is I, then the limit does not exist |
  216. | | | and nan is used to indicate that. |
  217. +--------------+---------+-----------------------------------------------+
  218. | oo**(1+I) | zoo | If the real part of e is positive, then the |
  219. | (-oo)**(1+I) | | limit of abs(x**e) is oo. So the limit value |
  220. | | | is zoo. |
  221. +--------------+---------+-----------------------------------------------+
  222. | oo**(-1+I) | 0 | If the real part of e is negative, then the |
  223. | -oo**(-1+I) | | limit is 0. |
  224. +--------------+---------+-----------------------------------------------+
  225. Because symbolic computations are more flexible than floating point
  226. calculations and we prefer to never return an incorrect answer,
  227. we choose not to conform to all IEEE 754 conventions. This helps
  228. us avoid extra test-case code in the calculation of limits.
  229. See Also
  230. ========
  231. sympy.core.numbers.Infinity
  232. sympy.core.numbers.NegativeInfinity
  233. sympy.core.numbers.NaN
  234. References
  235. ==========
  236. .. [1] https://en.wikipedia.org/wiki/Exponentiation
  237. .. [2] https://en.wikipedia.org/wiki/Exponentiation#Zero_to_the_power_of_zero
  238. .. [3] https://en.wikipedia.org/wiki/Indeterminate_forms
  239. """
  240. is_Pow = True
  241. __slots__ = ('is_commutative',)
  242. args: tTuple[Expr, Expr]
  243. @cacheit
  244. def __new__(cls, b, e, evaluate=None):
  245. if evaluate is None:
  246. evaluate = global_parameters.evaluate
  247. from sympy.functions.elementary.exponential import exp_polar
  248. b = _sympify(b)
  249. e = _sympify(e)
  250. # XXX: This can be removed when non-Expr args are disallowed rather
  251. # than deprecated.
  252. from .relational import Relational
  253. if isinstance(b, Relational) or isinstance(e, Relational):
  254. raise TypeError('Relational cannot be used in Pow')
  255. # XXX: This should raise TypeError once deprecation period is over:
  256. for arg in [b, e]:
  257. if not isinstance(arg, Expr):
  258. sympy_deprecation_warning(
  259. f"""
  260. Using non-Expr arguments in Pow is deprecated (in this case, one of the
  261. arguments is of type {type(arg).__name__!r}).
  262. If you really did intend to construct a power with this base, use the **
  263. operator instead.""",
  264. deprecated_since_version="1.7",
  265. active_deprecations_target="non-expr-args-deprecated",
  266. stacklevel=4,
  267. )
  268. if evaluate:
  269. if e is S.ComplexInfinity:
  270. return S.NaN
  271. if e is S.Infinity:
  272. if is_gt(b, S.One):
  273. return S.Infinity
  274. if is_gt(b, S.NegativeOne) and is_lt(b, S.One):
  275. return S.Zero
  276. if is_lt(b, S.NegativeOne):
  277. if b.is_finite:
  278. return S.ComplexInfinity
  279. if b.is_finite is False:
  280. return S.NaN
  281. if e is S.Zero:
  282. return S.One
  283. elif e is S.One:
  284. return b
  285. elif e == -1 and not b:
  286. return S.ComplexInfinity
  287. elif e.__class__.__name__ == "AccumulationBounds":
  288. if b == S.Exp1:
  289. from sympy.calculus.accumulationbounds import AccumBounds
  290. return AccumBounds(Pow(b, e.min), Pow(b, e.max))
  291. # autosimplification if base is a number and exp odd/even
  292. # if base is Number then the base will end up positive; we
  293. # do not do this with arbitrary expressions since symbolic
  294. # cancellation might occur as in (x - 1)/(1 - x) -> -1. If
  295. # we returned Piecewise((-1, Ne(x, 1))) for such cases then
  296. # we could do this...but we don't
  297. elif (e.is_Symbol and e.is_integer or e.is_Integer
  298. ) and (b.is_number and b.is_Mul or b.is_Number
  299. ) and b.could_extract_minus_sign():
  300. if e.is_even:
  301. b = -b
  302. elif e.is_odd:
  303. return -Pow(-b, e)
  304. if S.NaN in (b, e): # XXX S.NaN**x -> S.NaN under assumption that x != 0
  305. return S.NaN
  306. elif b is S.One:
  307. if abs(e).is_infinite:
  308. return S.NaN
  309. return S.One
  310. else:
  311. # recognize base as E
  312. if not e.is_Atom and b is not S.Exp1 and not isinstance(b, exp_polar):
  313. from .exprtools import factor_terms
  314. from sympy.functions.elementary.exponential import log
  315. from sympy.simplify.radsimp import fraction
  316. c, ex = factor_terms(e, sign=False).as_coeff_Mul()
  317. num, den = fraction(ex)
  318. if isinstance(den, log) and den.args[0] == b:
  319. return S.Exp1**(c*num)
  320. elif den.is_Add:
  321. from sympy.functions.elementary.complexes import sign, im
  322. s = sign(im(b))
  323. if s.is_Number and s and den == \
  324. log(-factor_terms(b, sign=False)) + s*S.ImaginaryUnit*S.Pi:
  325. return S.Exp1**(c*num)
  326. obj = b._eval_power(e)
  327. if obj is not None:
  328. return obj
  329. obj = Expr.__new__(cls, b, e)
  330. obj = cls._exec_constructor_postprocessors(obj)
  331. if not isinstance(obj, Pow):
  332. return obj
  333. obj.is_commutative = (b.is_commutative and e.is_commutative)
  334. return obj
  335. def inverse(self, argindex=1):
  336. if self.base == S.Exp1:
  337. from sympy.functions.elementary.exponential import log
  338. return log
  339. return None
  340. @property
  341. def base(self):
  342. return self._args[0]
  343. @property
  344. def exp(self):
  345. return self._args[1]
  346. @property
  347. def kind(self):
  348. if self.exp.kind is NumberKind:
  349. return self.base.kind
  350. else:
  351. return UndefinedKind
  352. @classmethod
  353. def class_key(cls):
  354. return 3, 2, cls.__name__
  355. def _eval_refine(self, assumptions):
  356. from sympy.assumptions.ask import ask, Q
  357. b, e = self.as_base_exp()
  358. if ask(Q.integer(e), assumptions) and b.could_extract_minus_sign():
  359. if ask(Q.even(e), assumptions):
  360. return Pow(-b, e)
  361. elif ask(Q.odd(e), assumptions):
  362. return -Pow(-b, e)
  363. def _eval_power(self, other):
  364. b, e = self.as_base_exp()
  365. if b is S.NaN:
  366. return (b**e)**other # let __new__ handle it
  367. s = None
  368. if other.is_integer:
  369. s = 1
  370. elif b.is_polar: # e.g. exp_polar, besselj, var('p', polar=True)...
  371. s = 1
  372. elif e.is_extended_real is not None:
  373. from sympy.functions.elementary.complexes import arg, im, re, sign
  374. from sympy.functions.elementary.exponential import exp, log
  375. from sympy.functions.elementary.integers import floor
  376. # helper functions ===========================
  377. def _half(e):
  378. """Return True if the exponent has a literal 2 as the
  379. denominator, else None."""
  380. if getattr(e, 'q', None) == 2:
  381. return True
  382. n, d = e.as_numer_denom()
  383. if n.is_integer and d == 2:
  384. return True
  385. def _n2(e):
  386. """Return ``e`` evaluated to a Number with 2 significant
  387. digits, else None."""
  388. try:
  389. rv = e.evalf(2, strict=True)
  390. if rv.is_Number:
  391. return rv
  392. except PrecisionExhausted:
  393. pass
  394. # ===================================================
  395. if e.is_extended_real:
  396. # we need _half(other) with constant floor or
  397. # floor(S.Half - e*arg(b)/2/pi) == 0
  398. # handle -1 as special case
  399. if e == -1:
  400. # floor arg. is 1/2 + arg(b)/2/pi
  401. if _half(other):
  402. if b.is_negative is True:
  403. return S.NegativeOne**other*Pow(-b, e*other)
  404. elif b.is_negative is False: # XXX ok if im(b) != 0?
  405. return Pow(b, -other)
  406. elif e.is_even:
  407. if b.is_extended_real:
  408. b = abs(b)
  409. if b.is_imaginary:
  410. b = abs(im(b))*S.ImaginaryUnit
  411. if (abs(e) < 1) == True or e == 1:
  412. s = 1 # floor = 0
  413. elif b.is_extended_nonnegative:
  414. s = 1 # floor = 0
  415. elif re(b).is_extended_nonnegative and (abs(e) < 2) == True:
  416. s = 1 # floor = 0
  417. elif fuzzy_not(im(b).is_zero) and abs(e) == 2:
  418. s = 1 # floor = 0
  419. elif _half(other):
  420. s = exp(2*S.Pi*S.ImaginaryUnit*other*floor(
  421. S.Half - e*arg(b)/(2*S.Pi)))
  422. if s.is_extended_real and _n2(sign(s) - s) == 0:
  423. s = sign(s)
  424. else:
  425. s = None
  426. else:
  427. # e.is_extended_real is False requires:
  428. # _half(other) with constant floor or
  429. # floor(S.Half - im(e*log(b))/2/pi) == 0
  430. try:
  431. s = exp(2*S.ImaginaryUnit*S.Pi*other*
  432. floor(S.Half - im(e*log(b))/2/S.Pi))
  433. # be careful to test that s is -1 or 1 b/c sign(I) == I:
  434. # so check that s is real
  435. if s.is_extended_real and _n2(sign(s) - s) == 0:
  436. s = sign(s)
  437. else:
  438. s = None
  439. except PrecisionExhausted:
  440. s = None
  441. if s is not None:
  442. return s*Pow(b, e*other)
  443. def _eval_Mod(self, q):
  444. r"""A dispatched function to compute `b^e \bmod q`, dispatched
  445. by ``Mod``.
  446. Notes
  447. =====
  448. Algorithms:
  449. 1. For unevaluated integer power, use built-in ``pow`` function
  450. with 3 arguments, if powers are not too large wrt base.
  451. 2. For very large powers, use totient reduction if $e \ge \log(m)$.
  452. Bound on m, is for safe factorization memory wise i.e. $m^{1/4}$.
  453. For pollard-rho to be faster than built-in pow $\log(e) > m^{1/4}$
  454. check is added.
  455. 3. For any unevaluated power found in `b` or `e`, the step 2
  456. will be recursed down to the base and the exponent
  457. such that the $b \bmod q$ becomes the new base and
  458. $\phi(q) + e \bmod \phi(q)$ becomes the new exponent, and then
  459. the computation for the reduced expression can be done.
  460. """
  461. base, exp = self.base, self.exp
  462. if exp.is_integer and exp.is_positive:
  463. if q.is_integer and base % q == 0:
  464. return S.Zero
  465. from sympy.ntheory.factor_ import totient
  466. if base.is_Integer and exp.is_Integer and q.is_Integer:
  467. b, e, m = int(base), int(exp), int(q)
  468. mb = m.bit_length()
  469. if mb <= 80 and e >= mb and e.bit_length()**4 >= m:
  470. phi = totient(m)
  471. return Integer(pow(b, phi + e%phi, m))
  472. return Integer(pow(b, e, m))
  473. from .mod import Mod
  474. if isinstance(base, Pow) and base.is_integer and base.is_number:
  475. base = Mod(base, q)
  476. return Mod(Pow(base, exp, evaluate=False), q)
  477. if isinstance(exp, Pow) and exp.is_integer and exp.is_number:
  478. bit_length = int(q).bit_length()
  479. # XXX Mod-Pow actually attempts to do a hanging evaluation
  480. # if this dispatched function returns None.
  481. # May need some fixes in the dispatcher itself.
  482. if bit_length <= 80:
  483. phi = totient(q)
  484. exp = phi + Mod(exp, phi)
  485. return Mod(Pow(base, exp, evaluate=False), q)
  486. def _eval_is_even(self):
  487. if self.exp.is_integer and self.exp.is_positive:
  488. return self.base.is_even
  489. def _eval_is_negative(self):
  490. ext_neg = Pow._eval_is_extended_negative(self)
  491. if ext_neg is True:
  492. return self.is_finite
  493. return ext_neg
  494. def _eval_is_positive(self):
  495. ext_pos = Pow._eval_is_extended_positive(self)
  496. if ext_pos is True:
  497. return self.is_finite
  498. return ext_pos
  499. def _eval_is_extended_positive(self):
  500. if self.base == self.exp:
  501. if self.base.is_extended_nonnegative:
  502. return True
  503. elif self.base.is_positive:
  504. if self.exp.is_real:
  505. return True
  506. elif self.base.is_extended_negative:
  507. if self.exp.is_even:
  508. return True
  509. if self.exp.is_odd:
  510. return False
  511. elif self.base.is_zero:
  512. if self.exp.is_extended_real:
  513. return self.exp.is_zero
  514. elif self.base.is_extended_nonpositive:
  515. if self.exp.is_odd:
  516. return False
  517. elif self.base.is_imaginary:
  518. if self.exp.is_integer:
  519. m = self.exp % 4
  520. if m.is_zero:
  521. return True
  522. if m.is_integer and m.is_zero is False:
  523. return False
  524. if self.exp.is_imaginary:
  525. from sympy.functions.elementary.exponential import log
  526. return log(self.base).is_imaginary
  527. def _eval_is_extended_negative(self):
  528. if self.exp is S.Half:
  529. if self.base.is_complex or self.base.is_extended_real:
  530. return False
  531. if self.base.is_extended_negative:
  532. if self.exp.is_odd and self.base.is_finite:
  533. return True
  534. if self.exp.is_even:
  535. return False
  536. elif self.base.is_extended_positive:
  537. if self.exp.is_extended_real:
  538. return False
  539. elif self.base.is_zero:
  540. if self.exp.is_extended_real:
  541. return False
  542. elif self.base.is_extended_nonnegative:
  543. if self.exp.is_extended_nonnegative:
  544. return False
  545. elif self.base.is_extended_nonpositive:
  546. if self.exp.is_even:
  547. return False
  548. elif self.base.is_extended_real:
  549. if self.exp.is_even:
  550. return False
  551. def _eval_is_zero(self):
  552. if self.base.is_zero:
  553. if self.exp.is_extended_positive:
  554. return True
  555. elif self.exp.is_extended_nonpositive:
  556. return False
  557. elif self.base == S.Exp1:
  558. return self.exp is S.NegativeInfinity
  559. elif self.base.is_zero is False:
  560. if self.base.is_finite and self.exp.is_finite:
  561. return False
  562. elif self.exp.is_negative:
  563. return self.base.is_infinite
  564. elif self.exp.is_nonnegative:
  565. return False
  566. elif self.exp.is_infinite and self.exp.is_extended_real:
  567. if (1 - abs(self.base)).is_extended_positive:
  568. return self.exp.is_extended_positive
  569. elif (1 - abs(self.base)).is_extended_negative:
  570. return self.exp.is_extended_negative
  571. elif self.base.is_finite and self.exp.is_negative:
  572. # when self.base.is_zero is None
  573. return False
  574. def _eval_is_integer(self):
  575. b, e = self.args
  576. if b.is_rational:
  577. if b.is_integer is False and e.is_positive:
  578. return False # rat**nonneg
  579. if b.is_integer and e.is_integer:
  580. if b is S.NegativeOne:
  581. return True
  582. if e.is_nonnegative or e.is_positive:
  583. return True
  584. if b.is_integer and e.is_negative and (e.is_finite or e.is_integer):
  585. if fuzzy_not((b - 1).is_zero) and fuzzy_not((b + 1).is_zero):
  586. return False
  587. if b.is_Number and e.is_Number:
  588. check = self.func(*self.args)
  589. return check.is_Integer
  590. if e.is_negative and b.is_positive and (b - 1).is_positive:
  591. return False
  592. if e.is_negative and b.is_negative and (b + 1).is_negative:
  593. return False
  594. def _eval_is_extended_real(self):
  595. if self.base is S.Exp1:
  596. if self.exp.is_extended_real:
  597. return True
  598. elif self.exp.is_imaginary:
  599. return (2*S.ImaginaryUnit*self.exp/S.Pi).is_even
  600. from sympy.functions.elementary.exponential import log, exp
  601. real_b = self.base.is_extended_real
  602. if real_b is None:
  603. if self.base.func == exp and self.base.exp.is_imaginary:
  604. return self.exp.is_imaginary
  605. if self.base.func == Pow and self.base.base is S.Exp1 and self.base.exp.is_imaginary:
  606. return self.exp.is_imaginary
  607. return
  608. real_e = self.exp.is_extended_real
  609. if real_e is None:
  610. return
  611. if real_b and real_e:
  612. if self.base.is_extended_positive:
  613. return True
  614. elif self.base.is_extended_nonnegative and self.exp.is_extended_nonnegative:
  615. return True
  616. elif self.exp.is_integer and self.base.is_extended_nonzero:
  617. return True
  618. elif self.exp.is_integer and self.exp.is_nonnegative:
  619. return True
  620. elif self.base.is_extended_negative:
  621. if self.exp.is_Rational:
  622. return False
  623. if real_e and self.exp.is_extended_negative and self.base.is_zero is False:
  624. return Pow(self.base, -self.exp).is_extended_real
  625. im_b = self.base.is_imaginary
  626. im_e = self.exp.is_imaginary
  627. if im_b:
  628. if self.exp.is_integer:
  629. if self.exp.is_even:
  630. return True
  631. elif self.exp.is_odd:
  632. return False
  633. elif im_e and log(self.base).is_imaginary:
  634. return True
  635. elif self.exp.is_Add:
  636. c, a = self.exp.as_coeff_Add()
  637. if c and c.is_Integer:
  638. return Mul(
  639. self.base**c, self.base**a, evaluate=False).is_extended_real
  640. elif self.base in (-S.ImaginaryUnit, S.ImaginaryUnit):
  641. if (self.exp/2).is_integer is False:
  642. return False
  643. if real_b and im_e:
  644. if self.base is S.NegativeOne:
  645. return True
  646. c = self.exp.coeff(S.ImaginaryUnit)
  647. if c:
  648. if self.base.is_rational and c.is_rational:
  649. if self.base.is_nonzero and (self.base - 1).is_nonzero and c.is_nonzero:
  650. return False
  651. ok = (c*log(self.base)/S.Pi).is_integer
  652. if ok is not None:
  653. return ok
  654. if real_b is False: # we already know it's not imag
  655. from sympy.functions.elementary.complexes import arg
  656. i = arg(self.base)*self.exp/S.Pi
  657. if i.is_complex: # finite
  658. return i.is_integer
  659. def _eval_is_complex(self):
  660. if self.base == S.Exp1:
  661. return fuzzy_or([self.exp.is_complex, self.exp.is_extended_negative])
  662. if all(a.is_complex for a in self.args) and self._eval_is_finite():
  663. return True
  664. def _eval_is_imaginary(self):
  665. if self.base.is_imaginary:
  666. if self.exp.is_integer:
  667. odd = self.exp.is_odd
  668. if odd is not None:
  669. return odd
  670. return
  671. if self.base == S.Exp1:
  672. f = 2 * self.exp / (S.Pi*S.ImaginaryUnit)
  673. # exp(pi*integer) = 1 or -1, so not imaginary
  674. if f.is_even:
  675. return False
  676. # exp(pi*integer + pi/2) = I or -I, so it is imaginary
  677. if f.is_odd:
  678. return True
  679. return None
  680. if self.exp.is_imaginary:
  681. from sympy.functions.elementary.exponential import log
  682. imlog = log(self.base).is_imaginary
  683. if imlog is not None:
  684. return False # I**i -> real; (2*I)**i -> complex ==> not imaginary
  685. if self.base.is_extended_real and self.exp.is_extended_real:
  686. if self.base.is_positive:
  687. return False
  688. else:
  689. rat = self.exp.is_rational
  690. if not rat:
  691. return rat
  692. if self.exp.is_integer:
  693. return False
  694. else:
  695. half = (2*self.exp).is_integer
  696. if half:
  697. return self.base.is_negative
  698. return half
  699. if self.base.is_extended_real is False: # we already know it's not imag
  700. from sympy.functions.elementary.complexes import arg
  701. i = arg(self.base)*self.exp/S.Pi
  702. isodd = (2*i).is_odd
  703. if isodd is not None:
  704. return isodd
  705. def _eval_is_odd(self):
  706. if self.exp.is_integer:
  707. if self.exp.is_positive:
  708. return self.base.is_odd
  709. elif self.exp.is_nonnegative and self.base.is_odd:
  710. return True
  711. elif self.base is S.NegativeOne:
  712. return True
  713. def _eval_is_finite(self):
  714. if self.exp.is_negative:
  715. if self.base.is_zero:
  716. return False
  717. if self.base.is_infinite or self.base.is_nonzero:
  718. return True
  719. c1 = self.base.is_finite
  720. if c1 is None:
  721. return
  722. c2 = self.exp.is_finite
  723. if c2 is None:
  724. return
  725. if c1 and c2:
  726. if self.exp.is_nonnegative or fuzzy_not(self.base.is_zero):
  727. return True
  728. def _eval_is_prime(self):
  729. '''
  730. An integer raised to the n(>=2)-th power cannot be a prime.
  731. '''
  732. if self.base.is_integer and self.exp.is_integer and (self.exp - 1).is_positive:
  733. return False
  734. def _eval_is_composite(self):
  735. """
  736. A power is composite if both base and exponent are greater than 1
  737. """
  738. if (self.base.is_integer and self.exp.is_integer and
  739. ((self.base - 1).is_positive and (self.exp - 1).is_positive or
  740. (self.base + 1).is_negative and self.exp.is_positive and self.exp.is_even)):
  741. return True
  742. def _eval_is_polar(self):
  743. return self.base.is_polar
  744. def _eval_subs(self, old, new):
  745. from sympy.calculus.accumulationbounds import AccumBounds
  746. if isinstance(self.exp, AccumBounds):
  747. b = self.base.subs(old, new)
  748. e = self.exp.subs(old, new)
  749. if isinstance(e, AccumBounds):
  750. return e.__rpow__(b)
  751. return self.func(b, e)
  752. from sympy.functions.elementary.exponential import exp, log
  753. def _check(ct1, ct2, old):
  754. """Return (bool, pow, remainder_pow) where, if bool is True, then the
  755. exponent of Pow `old` will combine with `pow` so the substitution
  756. is valid, otherwise bool will be False.
  757. For noncommutative objects, `pow` will be an integer, and a factor
  758. `Pow(old.base, remainder_pow)` needs to be included. If there is
  759. no such factor, None is returned. For commutative objects,
  760. remainder_pow is always None.
  761. cti are the coefficient and terms of an exponent of self or old
  762. In this _eval_subs routine a change like (b**(2*x)).subs(b**x, y)
  763. will give y**2 since (b**x)**2 == b**(2*x); if that equality does
  764. not hold then the substitution should not occur so `bool` will be
  765. False.
  766. """
  767. coeff1, terms1 = ct1
  768. coeff2, terms2 = ct2
  769. if terms1 == terms2:
  770. if old.is_commutative:
  771. # Allow fractional powers for commutative objects
  772. pow = coeff1/coeff2
  773. try:
  774. as_int(pow, strict=False)
  775. combines = True
  776. except ValueError:
  777. b, e = old.as_base_exp()
  778. # These conditions ensure that (b**e)**f == b**(e*f) for any f
  779. combines = b.is_positive and e.is_real or b.is_nonnegative and e.is_nonnegative
  780. return combines, pow, None
  781. else:
  782. # With noncommutative symbols, substitute only integer powers
  783. if not isinstance(terms1, tuple):
  784. terms1 = (terms1,)
  785. if not all(term.is_integer for term in terms1):
  786. return False, None, None
  787. try:
  788. # Round pow toward zero
  789. pow, remainder = divmod(as_int(coeff1), as_int(coeff2))
  790. if pow < 0 and remainder != 0:
  791. pow += 1
  792. remainder -= as_int(coeff2)
  793. if remainder == 0:
  794. remainder_pow = None
  795. else:
  796. remainder_pow = Mul(remainder, *terms1)
  797. return True, pow, remainder_pow
  798. except ValueError:
  799. # Can't substitute
  800. pass
  801. return False, None, None
  802. if old == self.base or (old == exp and self.base == S.Exp1):
  803. if new.is_Function and isinstance(new, Callable):
  804. return new(self.exp._subs(old, new))
  805. else:
  806. return new**self.exp._subs(old, new)
  807. # issue 10829: (4**x - 3*y + 2).subs(2**x, y) -> y**2 - 3*y + 2
  808. if isinstance(old, self.func) and self.exp == old.exp:
  809. l = log(self.base, old.base)
  810. if l.is_Number:
  811. return Pow(new, l)
  812. if isinstance(old, self.func) and self.base == old.base:
  813. if self.exp.is_Add is False:
  814. ct1 = self.exp.as_independent(Symbol, as_Add=False)
  815. ct2 = old.exp.as_independent(Symbol, as_Add=False)
  816. ok, pow, remainder_pow = _check(ct1, ct2, old)
  817. if ok:
  818. # issue 5180: (x**(6*y)).subs(x**(3*y),z)->z**2
  819. result = self.func(new, pow)
  820. if remainder_pow is not None:
  821. result = Mul(result, Pow(old.base, remainder_pow))
  822. return result
  823. else: # b**(6*x + a).subs(b**(3*x), y) -> y**2 * b**a
  824. # exp(exp(x) + exp(x**2)).subs(exp(exp(x)), w) -> w * exp(exp(x**2))
  825. oarg = old.exp
  826. new_l = []
  827. o_al = []
  828. ct2 = oarg.as_coeff_mul()
  829. for a in self.exp.args:
  830. newa = a._subs(old, new)
  831. ct1 = newa.as_coeff_mul()
  832. ok, pow, remainder_pow = _check(ct1, ct2, old)
  833. if ok:
  834. new_l.append(new**pow)
  835. if remainder_pow is not None:
  836. o_al.append(remainder_pow)
  837. continue
  838. elif not old.is_commutative and not newa.is_integer:
  839. # If any term in the exponent is non-integer,
  840. # we do not do any substitutions in the noncommutative case
  841. return
  842. o_al.append(newa)
  843. if new_l:
  844. expo = Add(*o_al)
  845. new_l.append(Pow(self.base, expo, evaluate=False) if expo != 1 else self.base)
  846. return Mul(*new_l)
  847. if (isinstance(old, exp) or (old.is_Pow and old.base is S.Exp1)) and self.exp.is_extended_real and self.base.is_positive:
  848. ct1 = old.exp.as_independent(Symbol, as_Add=False)
  849. ct2 = (self.exp*log(self.base)).as_independent(
  850. Symbol, as_Add=False)
  851. ok, pow, remainder_pow = _check(ct1, ct2, old)
  852. if ok:
  853. result = self.func(new, pow) # (2**x).subs(exp(x*log(2)), z) -> z
  854. if remainder_pow is not None:
  855. result = Mul(result, Pow(old.base, remainder_pow))
  856. return result
  857. def as_base_exp(self):
  858. """Return base and exp of self.
  859. Explanation
  860. ===========
  861. If base is 1/Integer, then return Integer, -exp. If this extra
  862. processing is not needed, the base and exp properties will
  863. give the raw arguments
  864. Examples
  865. ========
  866. >>> from sympy import Pow, S
  867. >>> p = Pow(S.Half, 2, evaluate=False)
  868. >>> p.as_base_exp()
  869. (2, -2)
  870. >>> p.args
  871. (1/2, 2)
  872. """
  873. b, e = self.args
  874. if b.is_Rational and b.p == 1 and b.q != 1:
  875. return Integer(b.q), -e
  876. return b, e
  877. def _eval_adjoint(self):
  878. from sympy.functions.elementary.complexes import adjoint
  879. i, p = self.exp.is_integer, self.base.is_positive
  880. if i:
  881. return adjoint(self.base)**self.exp
  882. if p:
  883. return self.base**adjoint(self.exp)
  884. if i is False and p is False:
  885. expanded = expand_complex(self)
  886. if expanded != self:
  887. return adjoint(expanded)
  888. def _eval_conjugate(self):
  889. from sympy.functions.elementary.complexes import conjugate as c
  890. i, p = self.exp.is_integer, self.base.is_positive
  891. if i:
  892. return c(self.base)**self.exp
  893. if p:
  894. return self.base**c(self.exp)
  895. if i is False and p is False:
  896. expanded = expand_complex(self)
  897. if expanded != self:
  898. return c(expanded)
  899. if self.is_extended_real:
  900. return self
  901. def _eval_transpose(self):
  902. from sympy.functions.elementary.complexes import transpose
  903. if self.base == S.Exp1:
  904. return self.func(S.Exp1, self.exp.transpose())
  905. i, p = self.exp.is_integer, (self.base.is_complex or self.base.is_infinite)
  906. if p:
  907. return self.base**self.exp
  908. if i:
  909. return transpose(self.base)**self.exp
  910. if i is False and p is False:
  911. expanded = expand_complex(self)
  912. if expanded != self:
  913. return transpose(expanded)
  914. def _eval_expand_power_exp(self, **hints):
  915. """a**(n + m) -> a**n*a**m"""
  916. b = self.base
  917. e = self.exp
  918. if b == S.Exp1:
  919. from sympy.concrete.summations import Sum
  920. if isinstance(e, Sum) and e.is_commutative:
  921. from sympy.concrete.products import Product
  922. return Product(self.func(b, e.function), *e.limits)
  923. if e.is_Add and e.is_commutative:
  924. expr = []
  925. for x in e.args:
  926. expr.append(self.func(b, x))
  927. return Mul(*expr)
  928. return self.func(b, e)
  929. def _eval_expand_power_base(self, **hints):
  930. """(a*b)**n -> a**n * b**n"""
  931. force = hints.get('force', False)
  932. b = self.base
  933. e = self.exp
  934. if not b.is_Mul:
  935. return self
  936. cargs, nc = b.args_cnc(split_1=False)
  937. # expand each term - this is top-level-only
  938. # expansion but we have to watch out for things
  939. # that don't have an _eval_expand method
  940. if nc:
  941. nc = [i._eval_expand_power_base(**hints)
  942. if hasattr(i, '_eval_expand_power_base') else i
  943. for i in nc]
  944. if e.is_Integer:
  945. if e.is_positive:
  946. rv = Mul(*nc*e)
  947. else:
  948. rv = Mul(*[i**-1 for i in nc[::-1]]*-e)
  949. if cargs:
  950. rv *= Mul(*cargs)**e
  951. return rv
  952. if not cargs:
  953. return self.func(Mul(*nc), e, evaluate=False)
  954. nc = [Mul(*nc)]
  955. # sift the commutative bases
  956. other, maybe_real = sift(cargs, lambda x: x.is_extended_real is False,
  957. binary=True)
  958. def pred(x):
  959. if x is S.ImaginaryUnit:
  960. return S.ImaginaryUnit
  961. polar = x.is_polar
  962. if polar:
  963. return True
  964. if polar is None:
  965. return fuzzy_bool(x.is_extended_nonnegative)
  966. sifted = sift(maybe_real, pred)
  967. nonneg = sifted[True]
  968. other += sifted[None]
  969. neg = sifted[False]
  970. imag = sifted[S.ImaginaryUnit]
  971. if imag:
  972. I = S.ImaginaryUnit
  973. i = len(imag) % 4
  974. if i == 0:
  975. pass
  976. elif i == 1:
  977. other.append(I)
  978. elif i == 2:
  979. if neg:
  980. nonn = -neg.pop()
  981. if nonn is not S.One:
  982. nonneg.append(nonn)
  983. else:
  984. neg.append(S.NegativeOne)
  985. else:
  986. if neg:
  987. nonn = -neg.pop()
  988. if nonn is not S.One:
  989. nonneg.append(nonn)
  990. else:
  991. neg.append(S.NegativeOne)
  992. other.append(I)
  993. del imag
  994. # bring out the bases that can be separated from the base
  995. if force or e.is_integer:
  996. # treat all commutatives the same and put nc in other
  997. cargs = nonneg + neg + other
  998. other = nc
  999. else:
  1000. # this is just like what is happening automatically, except
  1001. # that now we are doing it for an arbitrary exponent for which
  1002. # no automatic expansion is done
  1003. assert not e.is_Integer
  1004. # handle negatives by making them all positive and putting
  1005. # the residual -1 in other
  1006. if len(neg) > 1:
  1007. o = S.One
  1008. if not other and neg[0].is_Number:
  1009. o *= neg.pop(0)
  1010. if len(neg) % 2:
  1011. o = -o
  1012. for n in neg:
  1013. nonneg.append(-n)
  1014. if o is not S.One:
  1015. other.append(o)
  1016. elif neg and other:
  1017. if neg[0].is_Number and neg[0] is not S.NegativeOne:
  1018. other.append(S.NegativeOne)
  1019. nonneg.append(-neg[0])
  1020. else:
  1021. other.extend(neg)
  1022. else:
  1023. other.extend(neg)
  1024. del neg
  1025. cargs = nonneg
  1026. other += nc
  1027. rv = S.One
  1028. if cargs:
  1029. if e.is_Rational:
  1030. npow, cargs = sift(cargs, lambda x: x.is_Pow and
  1031. x.exp.is_Rational and x.base.is_number,
  1032. binary=True)
  1033. rv = Mul(*[self.func(b.func(*b.args), e) for b in npow])
  1034. rv *= Mul(*[self.func(b, e, evaluate=False) for b in cargs])
  1035. if other:
  1036. rv *= self.func(Mul(*other), e, evaluate=False)
  1037. return rv
  1038. def _eval_expand_multinomial(self, **hints):
  1039. """(a + b + ..)**n -> a**n + n*a**(n-1)*b + .., n is nonzero integer"""
  1040. base, exp = self.args
  1041. result = self
  1042. if exp.is_Rational and exp.p > 0 and base.is_Add:
  1043. if not exp.is_Integer:
  1044. n = Integer(exp.p // exp.q)
  1045. if not n:
  1046. return result
  1047. else:
  1048. radical, result = self.func(base, exp - n), []
  1049. expanded_base_n = self.func(base, n)
  1050. if expanded_base_n.is_Pow:
  1051. expanded_base_n = \
  1052. expanded_base_n._eval_expand_multinomial()
  1053. for term in Add.make_args(expanded_base_n):
  1054. result.append(term*radical)
  1055. return Add(*result)
  1056. n = int(exp)
  1057. if base.is_commutative:
  1058. order_terms, other_terms = [], []
  1059. for b in base.args:
  1060. if b.is_Order:
  1061. order_terms.append(b)
  1062. else:
  1063. other_terms.append(b)
  1064. if order_terms:
  1065. # (f(x) + O(x^n))^m -> f(x)^m + m*f(x)^{m-1} *O(x^n)
  1066. f = Add(*other_terms)
  1067. o = Add(*order_terms)
  1068. if n == 2:
  1069. return expand_multinomial(f**n, deep=False) + n*f*o
  1070. else:
  1071. g = expand_multinomial(f**(n - 1), deep=False)
  1072. return expand_mul(f*g, deep=False) + n*g*o
  1073. if base.is_number:
  1074. # Efficiently expand expressions of the form (a + b*I)**n
  1075. # where 'a' and 'b' are real numbers and 'n' is integer.
  1076. a, b = base.as_real_imag()
  1077. if a.is_Rational and b.is_Rational:
  1078. if not a.is_Integer:
  1079. if not b.is_Integer:
  1080. k = self.func(a.q * b.q, n)
  1081. a, b = a.p*b.q, a.q*b.p
  1082. else:
  1083. k = self.func(a.q, n)
  1084. a, b = a.p, a.q*b
  1085. elif not b.is_Integer:
  1086. k = self.func(b.q, n)
  1087. a, b = a*b.q, b.p
  1088. else:
  1089. k = 1
  1090. a, b, c, d = int(a), int(b), 1, 0
  1091. while n:
  1092. if n & 1:
  1093. c, d = a*c - b*d, b*c + a*d
  1094. n -= 1
  1095. a, b = a*a - b*b, 2*a*b
  1096. n //= 2
  1097. I = S.ImaginaryUnit
  1098. if k == 1:
  1099. return c + I*d
  1100. else:
  1101. return Integer(c)/k + I*d/k
  1102. p = other_terms
  1103. # (x + y)**3 -> x**3 + 3*x**2*y + 3*x*y**2 + y**3
  1104. # in this particular example:
  1105. # p = [x,y]; n = 3
  1106. # so now it's easy to get the correct result -- we get the
  1107. # coefficients first:
  1108. from sympy.ntheory.multinomial import multinomial_coefficients
  1109. from sympy.polys.polyutils import basic_from_dict
  1110. expansion_dict = multinomial_coefficients(len(p), n)
  1111. # in our example: {(3, 0): 1, (1, 2): 3, (0, 3): 1, (2, 1): 3}
  1112. # and now construct the expression.
  1113. return basic_from_dict(expansion_dict, *p)
  1114. else:
  1115. if n == 2:
  1116. return Add(*[f*g for f in base.args for g in base.args])
  1117. else:
  1118. multi = (base**(n - 1))._eval_expand_multinomial()
  1119. if multi.is_Add:
  1120. return Add(*[f*g for f in base.args
  1121. for g in multi.args])
  1122. else:
  1123. # XXX can this ever happen if base was an Add?
  1124. return Add(*[f*multi for f in base.args])
  1125. elif (exp.is_Rational and exp.p < 0 and base.is_Add and
  1126. abs(exp.p) > exp.q):
  1127. return 1 / self.func(base, -exp)._eval_expand_multinomial()
  1128. elif exp.is_Add and base.is_Number:
  1129. # a + b a b
  1130. # n --> n n, where n, a, b are Numbers
  1131. coeff, tail = S.One, S.Zero
  1132. for term in exp.args:
  1133. if term.is_Number:
  1134. coeff *= self.func(base, term)
  1135. else:
  1136. tail += term
  1137. return coeff * self.func(base, tail)
  1138. else:
  1139. return result
  1140. def as_real_imag(self, deep=True, **hints):
  1141. if self.exp.is_Integer:
  1142. from sympy.polys.polytools import poly
  1143. exp = self.exp
  1144. re_e, im_e = self.base.as_real_imag(deep=deep)
  1145. if not im_e:
  1146. return self, S.Zero
  1147. a, b = symbols('a b', cls=Dummy)
  1148. if exp >= 0:
  1149. if re_e.is_Number and im_e.is_Number:
  1150. # We can be more efficient in this case
  1151. expr = expand_multinomial(self.base**exp)
  1152. if expr != self:
  1153. return expr.as_real_imag()
  1154. expr = poly(
  1155. (a + b)**exp) # a = re, b = im; expr = (a + b*I)**exp
  1156. else:
  1157. mag = re_e**2 + im_e**2
  1158. re_e, im_e = re_e/mag, -im_e/mag
  1159. if re_e.is_Number and im_e.is_Number:
  1160. # We can be more efficient in this case
  1161. expr = expand_multinomial((re_e + im_e*S.ImaginaryUnit)**-exp)
  1162. if expr != self:
  1163. return expr.as_real_imag()
  1164. expr = poly((a + b)**-exp)
  1165. # Terms with even b powers will be real
  1166. r = [i for i in expr.terms() if not i[0][1] % 2]
  1167. re_part = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
  1168. # Terms with odd b powers will be imaginary
  1169. r = [i for i in expr.terms() if i[0][1] % 4 == 1]
  1170. im_part1 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
  1171. r = [i for i in expr.terms() if i[0][1] % 4 == 3]
  1172. im_part3 = Add(*[cc*a**aa*b**bb for (aa, bb), cc in r])
  1173. return (re_part.subs({a: re_e, b: S.ImaginaryUnit*im_e}),
  1174. im_part1.subs({a: re_e, b: im_e}) + im_part3.subs({a: re_e, b: -im_e}))
  1175. from sympy.functions.elementary.trigonometric import atan2, cos, sin
  1176. if self.exp.is_Rational:
  1177. re_e, im_e = self.base.as_real_imag(deep=deep)
  1178. if im_e.is_zero and self.exp is S.Half:
  1179. if re_e.is_extended_nonnegative:
  1180. return self, S.Zero
  1181. if re_e.is_extended_nonpositive:
  1182. return S.Zero, (-self.base)**self.exp
  1183. # XXX: This is not totally correct since for x**(p/q) with
  1184. # x being imaginary there are actually q roots, but
  1185. # only a single one is returned from here.
  1186. r = self.func(self.func(re_e, 2) + self.func(im_e, 2), S.Half)
  1187. t = atan2(im_e, re_e)
  1188. rp, tp = self.func(r, self.exp), t*self.exp
  1189. return rp*cos(tp), rp*sin(tp)
  1190. elif self.base is S.Exp1:
  1191. from sympy.functions.elementary.exponential import exp
  1192. re_e, im_e = self.exp.as_real_imag()
  1193. if deep:
  1194. re_e = re_e.expand(deep, **hints)
  1195. im_e = im_e.expand(deep, **hints)
  1196. c, s = cos(im_e), sin(im_e)
  1197. return exp(re_e)*c, exp(re_e)*s
  1198. else:
  1199. from sympy.functions.elementary.complexes import im, re
  1200. if deep:
  1201. hints['complex'] = False
  1202. expanded = self.expand(deep, **hints)
  1203. if hints.get('ignore') == expanded:
  1204. return None
  1205. else:
  1206. return (re(expanded), im(expanded))
  1207. else:
  1208. return re(self), im(self)
  1209. def _eval_derivative(self, s):
  1210. from sympy.functions.elementary.exponential import log
  1211. dbase = self.base.diff(s)
  1212. dexp = self.exp.diff(s)
  1213. return self * (dexp * log(self.base) + dbase * self.exp/self.base)
  1214. def _eval_evalf(self, prec):
  1215. base, exp = self.as_base_exp()
  1216. if base == S.Exp1:
  1217. # Use mpmath function associated to class "exp":
  1218. from sympy.functions.elementary.exponential import exp as exp_function
  1219. return exp_function(self.exp, evaluate=False)._eval_evalf(prec)
  1220. base = base._evalf(prec)
  1221. if not exp.is_Integer:
  1222. exp = exp._evalf(prec)
  1223. if exp.is_negative and base.is_number and base.is_extended_real is False:
  1224. base = base.conjugate() / (base * base.conjugate())._evalf(prec)
  1225. exp = -exp
  1226. return self.func(base, exp).expand()
  1227. return self.func(base, exp)
  1228. def _eval_is_polynomial(self, syms):
  1229. if self.exp.has(*syms):
  1230. return False
  1231. if self.base.has(*syms):
  1232. return bool(self.base._eval_is_polynomial(syms) and
  1233. self.exp.is_Integer and (self.exp >= 0))
  1234. else:
  1235. return True
  1236. def _eval_is_rational(self):
  1237. # The evaluation of self.func below can be very expensive in the case
  1238. # of integer**integer if the exponent is large. We should try to exit
  1239. # before that if possible:
  1240. if (self.exp.is_integer and self.base.is_rational
  1241. and fuzzy_not(fuzzy_and([self.exp.is_negative, self.base.is_zero]))):
  1242. return True
  1243. p = self.func(*self.as_base_exp()) # in case it's unevaluated
  1244. if not p.is_Pow:
  1245. return p.is_rational
  1246. b, e = p.as_base_exp()
  1247. if e.is_Rational and b.is_Rational:
  1248. # we didn't check that e is not an Integer
  1249. # because Rational**Integer autosimplifies
  1250. return False
  1251. if e.is_integer:
  1252. if b.is_rational:
  1253. if fuzzy_not(b.is_zero) or e.is_nonnegative:
  1254. return True
  1255. if b == e: # always rational, even for 0**0
  1256. return True
  1257. elif b.is_irrational:
  1258. return e.is_zero
  1259. if b is S.Exp1:
  1260. if e.is_rational and e.is_nonzero:
  1261. return False
  1262. def _eval_is_algebraic(self):
  1263. def _is_one(expr):
  1264. try:
  1265. return (expr - 1).is_zero
  1266. except ValueError:
  1267. # when the operation is not allowed
  1268. return False
  1269. if self.base.is_zero or _is_one(self.base):
  1270. return True
  1271. elif self.base is S.Exp1:
  1272. s = self.func(*self.args)
  1273. if s.func == self.func:
  1274. if self.exp.is_nonzero:
  1275. if self.exp.is_algebraic:
  1276. return False
  1277. elif (self.exp/S.Pi).is_rational:
  1278. return False
  1279. elif (self.exp/(S.ImaginaryUnit*S.Pi)).is_rational:
  1280. return True
  1281. else:
  1282. return s.is_algebraic
  1283. elif self.exp.is_rational:
  1284. if self.base.is_algebraic is False:
  1285. return self.exp.is_zero
  1286. if self.base.is_zero is False:
  1287. if self.exp.is_nonzero:
  1288. return self.base.is_algebraic
  1289. elif self.base.is_algebraic:
  1290. return True
  1291. if self.exp.is_positive:
  1292. return self.base.is_algebraic
  1293. elif self.base.is_algebraic and self.exp.is_algebraic:
  1294. if ((fuzzy_not(self.base.is_zero)
  1295. and fuzzy_not(_is_one(self.base)))
  1296. or self.base.is_integer is False
  1297. or self.base.is_irrational):
  1298. return self.exp.is_rational
  1299. def _eval_is_rational_function(self, syms):
  1300. if self.exp.has(*syms):
  1301. return False
  1302. if self.base.has(*syms):
  1303. return self.base._eval_is_rational_function(syms) and \
  1304. self.exp.is_Integer
  1305. else:
  1306. return True
  1307. def _eval_is_meromorphic(self, x, a):
  1308. # f**g is meromorphic if g is an integer and f is meromorphic.
  1309. # E**(log(f)*g) is meromorphic if log(f)*g is meromorphic
  1310. # and finite.
  1311. base_merom = self.base._eval_is_meromorphic(x, a)
  1312. exp_integer = self.exp.is_Integer
  1313. if exp_integer:
  1314. return base_merom
  1315. exp_merom = self.exp._eval_is_meromorphic(x, a)
  1316. if base_merom is False:
  1317. # f**g = E**(log(f)*g) may be meromorphic if the
  1318. # singularities of log(f) and g cancel each other,
  1319. # for example, if g = 1/log(f). Hence,
  1320. return False if exp_merom else None
  1321. elif base_merom is None:
  1322. return None
  1323. b = self.base.subs(x, a)
  1324. # b is extended complex as base is meromorphic.
  1325. # log(base) is finite and meromorphic when b != 0, zoo.
  1326. b_zero = b.is_zero
  1327. if b_zero:
  1328. log_defined = False
  1329. else:
  1330. log_defined = fuzzy_and((b.is_finite, fuzzy_not(b_zero)))
  1331. if log_defined is False: # zero or pole of base
  1332. return exp_integer # False or None
  1333. elif log_defined is None:
  1334. return None
  1335. if not exp_merom:
  1336. return exp_merom # False or None
  1337. return self.exp.subs(x, a).is_finite
  1338. def _eval_is_algebraic_expr(self, syms):
  1339. if self.exp.has(*syms):
  1340. return False
  1341. if self.base.has(*syms):
  1342. return self.base._eval_is_algebraic_expr(syms) and \
  1343. self.exp.is_Rational
  1344. else:
  1345. return True
  1346. def _eval_rewrite_as_exp(self, base, expo, **kwargs):
  1347. from sympy.functions.elementary.exponential import exp, log
  1348. if base.is_zero or base.has(exp) or expo.has(exp):
  1349. return base**expo
  1350. if base.has(Symbol):
  1351. # delay evaluation if expo is non symbolic
  1352. # (as exp(x*log(5)) automatically reduces to x**5)
  1353. if global_parameters.exp_is_pow:
  1354. return Pow(S.Exp1, log(base)*expo, evaluate=expo.has(Symbol))
  1355. else:
  1356. return exp(log(base)*expo, evaluate=expo.has(Symbol))
  1357. else:
  1358. from sympy.functions.elementary.complexes import arg, Abs
  1359. return exp((log(Abs(base)) + S.ImaginaryUnit*arg(base))*expo)
  1360. def as_numer_denom(self):
  1361. if not self.is_commutative:
  1362. return self, S.One
  1363. base, exp = self.as_base_exp()
  1364. n, d = base.as_numer_denom()
  1365. # this should be the same as ExpBase.as_numer_denom wrt
  1366. # exponent handling
  1367. neg_exp = exp.is_negative
  1368. if exp.is_Mul and not neg_exp and not exp.is_positive:
  1369. neg_exp = exp.could_extract_minus_sign()
  1370. int_exp = exp.is_integer
  1371. # the denominator cannot be separated from the numerator if
  1372. # its sign is unknown unless the exponent is an integer, e.g.
  1373. # sqrt(a/b) != sqrt(a)/sqrt(b) when a=1 and b=-1. But if the
  1374. # denominator is negative the numerator and denominator can
  1375. # be negated and the denominator (now positive) separated.
  1376. if not (d.is_extended_real or int_exp):
  1377. n = base
  1378. d = S.One
  1379. dnonpos = d.is_nonpositive
  1380. if dnonpos:
  1381. n, d = -n, -d
  1382. elif dnonpos is None and not int_exp:
  1383. n = base
  1384. d = S.One
  1385. if neg_exp:
  1386. n, d = d, n
  1387. exp = -exp
  1388. if exp.is_infinite:
  1389. if n is S.One and d is not S.One:
  1390. return n, self.func(d, exp)
  1391. if n is not S.One and d is S.One:
  1392. return self.func(n, exp), d
  1393. return self.func(n, exp), self.func(d, exp)
  1394. def matches(self, expr, repl_dict=None, old=False):
  1395. expr = _sympify(expr)
  1396. if repl_dict is None:
  1397. repl_dict = dict()
  1398. # special case, pattern = 1 and expr.exp can match to 0
  1399. if expr is S.One:
  1400. d = self.exp.matches(S.Zero, repl_dict)
  1401. if d is not None:
  1402. return d
  1403. # make sure the expression to be matched is an Expr
  1404. if not isinstance(expr, Expr):
  1405. return None
  1406. b, e = expr.as_base_exp()
  1407. # special case number
  1408. sb, se = self.as_base_exp()
  1409. if sb.is_Symbol and se.is_Integer and expr:
  1410. if e.is_rational:
  1411. return sb.matches(b**(e/se), repl_dict)
  1412. return sb.matches(expr**(1/se), repl_dict)
  1413. d = repl_dict.copy()
  1414. d = self.base.matches(b, d)
  1415. if d is None:
  1416. return None
  1417. d = self.exp.xreplace(d).matches(e, d)
  1418. if d is None:
  1419. return Expr.matches(self, expr, repl_dict)
  1420. return d
  1421. def _eval_nseries(self, x, n, logx, cdir=0):
  1422. # NOTE! This function is an important part of the gruntz algorithm
  1423. # for computing limits. It has to return a generalized power
  1424. # series with coefficients in C(log, log(x)). In more detail:
  1425. # It has to return an expression
  1426. # c_0*x**e_0 + c_1*x**e_1 + ... (finitely many terms)
  1427. # where e_i are numbers (not necessarily integers) and c_i are
  1428. # expressions involving only numbers, the log function, and log(x).
  1429. # The series expansion of b**e is computed as follows:
  1430. # 1) We express b as f*(1 + g) where f is the leading term of b.
  1431. # g has order O(x**d) where d is strictly positive.
  1432. # 2) Then b**e = (f**e)*((1 + g)**e).
  1433. # (1 + g)**e is computed using binomial series.
  1434. from sympy.functions.elementary.exponential import exp, log
  1435. from sympy.series.limits import limit
  1436. from sympy.series.order import Order
  1437. if self.base is S.Exp1:
  1438. e_series = self.exp.nseries(x, n=n, logx=logx)
  1439. if e_series.is_Order:
  1440. return 1 + e_series
  1441. e0 = limit(e_series.removeO(), x, 0)
  1442. if e0 is S.NegativeInfinity:
  1443. return Order(x**n, x)
  1444. if e0 is S.Infinity:
  1445. return self
  1446. t = e_series - e0
  1447. exp_series = term = exp(e0)
  1448. # series of exp(e0 + t) in t
  1449. for i in range(1, n):
  1450. term *= t/i
  1451. term = term.nseries(x, n=n, logx=logx)
  1452. exp_series += term
  1453. exp_series += Order(t**n, x)
  1454. from sympy.simplify.powsimp import powsimp
  1455. return powsimp(exp_series, deep=True, combine='exp')
  1456. from sympy.simplify.powsimp import powdenest
  1457. self = powdenest(self, force=True).trigsimp()
  1458. b, e = self.as_base_exp()
  1459. if e.has(S.Infinity, S.NegativeInfinity, S.ComplexInfinity, S.NaN):
  1460. raise PoleError()
  1461. if e.has(x):
  1462. return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
  1463. if logx is not None and b.has(log):
  1464. from .symbol import Wild
  1465. c, ex = symbols('c, ex', cls=Wild, exclude=[x])
  1466. b = b.replace(log(c*x**ex), log(c) + ex*logx)
  1467. self = b**e
  1468. b = b.removeO()
  1469. try:
  1470. from sympy.functions.special.gamma_functions import polygamma
  1471. if b.has(polygamma, S.EulerGamma) and logx is not None:
  1472. raise ValueError()
  1473. _, m = b.leadterm(x)
  1474. except (ValueError, NotImplementedError, PoleError):
  1475. b = b._eval_nseries(x, n=max(2, n), logx=logx, cdir=cdir).removeO()
  1476. if b.has(S.NaN, S.ComplexInfinity):
  1477. raise NotImplementedError()
  1478. _, m = b.leadterm(x)
  1479. if e.has(log):
  1480. from sympy.simplify.simplify import logcombine
  1481. e = logcombine(e).cancel()
  1482. if not (m.is_zero or e.is_number and e.is_real):
  1483. return exp(e*log(b))._eval_nseries(x, n=n, logx=logx, cdir=cdir)
  1484. f = b.as_leading_term(x, logx=logx)
  1485. g = (b/f - S.One).cancel(expand=False)
  1486. if not m.is_number:
  1487. raise NotImplementedError()
  1488. maxpow = n - m*e
  1489. if maxpow.is_negative:
  1490. return Order(x**(m*e), x)
  1491. if g.is_zero:
  1492. r = f**e
  1493. if r != self:
  1494. r += Order(x**n, x)
  1495. return r
  1496. def coeff_exp(term, x):
  1497. coeff, exp = S.One, S.Zero
  1498. for factor in Mul.make_args(term):
  1499. if factor.has(x):
  1500. base, exp = factor.as_base_exp()
  1501. if base != x:
  1502. try:
  1503. return term.leadterm(x)
  1504. except ValueError:
  1505. return term, S.Zero
  1506. else:
  1507. coeff *= factor
  1508. return coeff, exp
  1509. def mul(d1, d2):
  1510. res = {}
  1511. for e1, e2 in product(d1, d2):
  1512. ex = e1 + e2
  1513. if ex < maxpow:
  1514. res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
  1515. return res
  1516. try:
  1517. _, d = g.leadterm(x)
  1518. except (ValueError, NotImplementedError):
  1519. if limit(g/x**maxpow, x, 0) == 0:
  1520. # g has higher order zero
  1521. return f**e + e*f**e*g # first term of binomial series
  1522. else:
  1523. raise NotImplementedError()
  1524. if not d.is_positive:
  1525. g = g.simplify()
  1526. _, d = g.leadterm(x)
  1527. if not d.is_positive:
  1528. raise NotImplementedError()
  1529. from sympy.functions.elementary.integers import ceiling
  1530. gpoly = g._eval_nseries(x, n=ceiling(maxpow), logx=logx, cdir=cdir).removeO()
  1531. gterms = {}
  1532. for term in Add.make_args(gpoly):
  1533. co1, e1 = coeff_exp(term, x)
  1534. gterms[e1] = gterms.get(e1, S.Zero) + co1
  1535. k = S.One
  1536. terms = {S.Zero: S.One}
  1537. tk = gterms
  1538. from sympy.functions.combinatorial.factorials import factorial, ff
  1539. while (k*d - maxpow).is_negative:
  1540. coeff = ff(e, k)/factorial(k)
  1541. for ex in tk:
  1542. terms[ex] = terms.get(ex, S.Zero) + coeff*tk[ex]
  1543. tk = mul(tk, gterms)
  1544. k += S.One
  1545. from sympy.functions.elementary.complexes import im
  1546. if (not e.is_integer and m.is_zero and f.is_real
  1547. and f.is_negative and im((b - f).dir(x, cdir)).is_negative):
  1548. inco, inex = coeff_exp(f**e*exp(-2*e*S.Pi*S.ImaginaryUnit), x)
  1549. else:
  1550. inco, inex = coeff_exp(f**e, x)
  1551. res = S.Zero
  1552. for e1 in terms:
  1553. ex = e1 + inex
  1554. res += terms[e1]*inco*x**(ex)
  1555. if not (e.is_integer and e.is_positive and (e*d - n).is_nonpositive and
  1556. res == _mexpand(self)):
  1557. res += Order(x**n, x)
  1558. return res
  1559. def _eval_as_leading_term(self, x, logx=None, cdir=0):
  1560. from sympy.functions.elementary.exponential import exp, log
  1561. e = self.exp
  1562. b = self.base
  1563. if self.base is S.Exp1:
  1564. arg = e.as_leading_term(x, logx=logx)
  1565. arg0 = arg.subs(x, 0)
  1566. if arg0 is S.NaN:
  1567. arg0 = arg.limit(x, 0)
  1568. if arg0.is_infinite is False:
  1569. return S.Exp1**arg0
  1570. raise PoleError("Cannot expand %s around 0" % (self))
  1571. elif e.has(x):
  1572. lt = exp(e * log(b))
  1573. try:
  1574. lt = lt.as_leading_term(x, logx=logx, cdir=cdir)
  1575. except PoleError:
  1576. pass
  1577. return lt
  1578. else:
  1579. from sympy.functions.elementary.complexes import im
  1580. f = b.as_leading_term(x, logx=logx, cdir=cdir)
  1581. if (not e.is_integer and f.is_constant() and f.is_real
  1582. and f.is_negative and im((b - f).dir(x, cdir)).is_negative):
  1583. return self.func(f, e) * exp(-2 * e * S.Pi * S.ImaginaryUnit)
  1584. return self.func(f, e)
  1585. @cacheit
  1586. def _taylor_term(self, n, x, *previous_terms): # of (1 + x)**e
  1587. from sympy.functions.combinatorial.factorials import binomial
  1588. return binomial(self.exp, n) * self.func(x, n)
  1589. def taylor_term(self, n, x, *previous_terms):
  1590. if self.base is not S.Exp1:
  1591. return super().taylor_term(n, x, *previous_terms)
  1592. if n < 0:
  1593. return S.Zero
  1594. if n == 0:
  1595. return S.One
  1596. from .sympify import sympify
  1597. x = sympify(x)
  1598. if previous_terms:
  1599. p = previous_terms[-1]
  1600. if p is not None:
  1601. return p * x / n
  1602. from sympy.functions.combinatorial.factorials import factorial
  1603. return x**n/factorial(n)
  1604. def _eval_rewrite_as_sin(self, base, exp):
  1605. if self.base is S.Exp1:
  1606. from sympy.functions.elementary.trigonometric import sin
  1607. return sin(S.ImaginaryUnit*self.exp + S.Pi/2) - S.ImaginaryUnit*sin(S.ImaginaryUnit*self.exp)
  1608. def _eval_rewrite_as_cos(self, base, exp):
  1609. if self.base is S.Exp1:
  1610. from sympy.functions.elementary.trigonometric import cos
  1611. return cos(S.ImaginaryUnit*self.exp) + S.ImaginaryUnit*cos(S.ImaginaryUnit*self.exp + S.Pi/2)
  1612. def _eval_rewrite_as_tanh(self, base, exp):
  1613. if self.base is S.Exp1:
  1614. from sympy.functions.elementary.trigonometric import tanh
  1615. return (1 + tanh(self.exp/2))/(1 - tanh(self.exp/2))
  1616. def _eval_rewrite_as_sqrt(self, base, exp, **kwargs):
  1617. from sympy.functions.elementary.trigonometric import sin, cos
  1618. if base is not S.Exp1:
  1619. return None
  1620. if exp.is_Mul:
  1621. coeff = exp.coeff(S.Pi * S.ImaginaryUnit)
  1622. if coeff and coeff.is_number:
  1623. cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff)
  1624. if not isinstance(cosine, cos) and not isinstance (sine, sin):
  1625. return cosine + S.ImaginaryUnit*sine
  1626. def as_content_primitive(self, radical=False, clear=True):
  1627. """Return the tuple (R, self/R) where R is the positive Rational
  1628. extracted from self.
  1629. Examples
  1630. ========
  1631. >>> from sympy import sqrt
  1632. >>> sqrt(4 + 4*sqrt(2)).as_content_primitive()
  1633. (2, sqrt(1 + sqrt(2)))
  1634. >>> sqrt(3 + 3*sqrt(2)).as_content_primitive()
  1635. (1, sqrt(3)*sqrt(1 + sqrt(2)))
  1636. >>> from sympy import expand_power_base, powsimp, Mul
  1637. >>> from sympy.abc import x, y
  1638. >>> ((2*x + 2)**2).as_content_primitive()
  1639. (4, (x + 1)**2)
  1640. >>> (4**((1 + y)/2)).as_content_primitive()
  1641. (2, 4**(y/2))
  1642. >>> (3**((1 + y)/2)).as_content_primitive()
  1643. (1, 3**((y + 1)/2))
  1644. >>> (3**((5 + y)/2)).as_content_primitive()
  1645. (9, 3**((y + 1)/2))
  1646. >>> eq = 3**(2 + 2*x)
  1647. >>> powsimp(eq) == eq
  1648. True
  1649. >>> eq.as_content_primitive()
  1650. (9, 3**(2*x))
  1651. >>> powsimp(Mul(*_))
  1652. 3**(2*x + 2)
  1653. >>> eq = (2 + 2*x)**y
  1654. >>> s = expand_power_base(eq); s.is_Mul, s
  1655. (False, (2*x + 2)**y)
  1656. >>> eq.as_content_primitive()
  1657. (1, (2*(x + 1))**y)
  1658. >>> s = expand_power_base(_[1]); s.is_Mul, s
  1659. (True, 2**y*(x + 1)**y)
  1660. See docstring of Expr.as_content_primitive for more examples.
  1661. """
  1662. b, e = self.as_base_exp()
  1663. b = _keep_coeff(*b.as_content_primitive(radical=radical, clear=clear))
  1664. ce, pe = e.as_content_primitive(radical=radical, clear=clear)
  1665. if b.is_Rational:
  1666. #e
  1667. #= ce*pe
  1668. #= ce*(h + t)
  1669. #= ce*h + ce*t
  1670. #=> self
  1671. #= b**(ce*h)*b**(ce*t)
  1672. #= b**(cehp/cehq)*b**(ce*t)
  1673. #= b**(iceh + r/cehq)*b**(ce*t)
  1674. #= b**(iceh)*b**(r/cehq)*b**(ce*t)
  1675. #= b**(iceh)*b**(ce*t + r/cehq)
  1676. h, t = pe.as_coeff_Add()
  1677. if h.is_Rational and b != S.Zero:
  1678. ceh = ce*h
  1679. c = self.func(b, ceh)
  1680. r = S.Zero
  1681. if not c.is_Rational:
  1682. iceh, r = divmod(ceh.p, ceh.q)
  1683. c = self.func(b, iceh)
  1684. return c, self.func(b, _keep_coeff(ce, t + r/ce/ceh.q))
  1685. e = _keep_coeff(ce, pe)
  1686. # b**e = (h*t)**e = h**e*t**e = c*m*t**e
  1687. if e.is_Rational and b.is_Mul:
  1688. h, t = b.as_content_primitive(radical=radical, clear=clear) # h is positive
  1689. c, m = self.func(h, e).as_coeff_Mul() # so c is positive
  1690. m, me = m.as_base_exp()
  1691. if m is S.One or me == e: # probably always true
  1692. # return the following, not return c, m*Pow(t, e)
  1693. # which would change Pow into Mul; we let SymPy
  1694. # decide what to do by using the unevaluated Mul, e.g
  1695. # should it stay as sqrt(2 + 2*sqrt(5)) or become
  1696. # sqrt(2)*sqrt(1 + sqrt(5))
  1697. return c, self.func(_keep_coeff(m, t), e)
  1698. return S.One, self.func(b, e)
  1699. def is_constant(self, *wrt, **flags):
  1700. expr = self
  1701. if flags.get('simplify', True):
  1702. expr = expr.simplify()
  1703. b, e = expr.as_base_exp()
  1704. bz = b.equals(0)
  1705. if bz: # recalculate with assumptions in case it's unevaluated
  1706. new = b**e
  1707. if new != expr:
  1708. return new.is_constant()
  1709. econ = e.is_constant(*wrt)
  1710. bcon = b.is_constant(*wrt)
  1711. if bcon:
  1712. if econ:
  1713. return True
  1714. bz = b.equals(0)
  1715. if bz is False:
  1716. return False
  1717. elif bcon is None:
  1718. return None
  1719. return e.equals(0)
  1720. def _eval_difference_delta(self, n, step):
  1721. b, e = self.args
  1722. if e.has(n) and not b.has(n):
  1723. new_e = e.subs(n, n + step)
  1724. return (b**(new_e - e) - 1) * self
  1725. power = Dispatcher('power')
  1726. power.add((object, object), Pow)
  1727. from .add import Add
  1728. from .numbers import Integer
  1729. from .mul import Mul, _keep_coeff
  1730. from .symbol import Symbol, Dummy, symbols