power.py 75 KB

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