power.py 72 KB

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