exponential.py 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291
  1. from itertools import product
  2. from typing import Tuple as tTuple
  3. from sympy.core.add import Add
  4. from sympy.core.cache import cacheit
  5. from sympy.core.expr import Expr
  6. from sympy.core.function import (Function, ArgumentIndexError, expand_log,
  7. expand_mul, FunctionClass, PoleError, expand_multinomial, expand_complex)
  8. from sympy.core.logic import fuzzy_and, fuzzy_not, fuzzy_or
  9. from sympy.core.mul import Mul
  10. from sympy.core.numbers import Integer, Rational, pi, I, ImaginaryUnit
  11. from sympy.core.parameters import global_parameters
  12. from sympy.core.power import Pow
  13. from sympy.core.singleton import S
  14. from sympy.core.symbol import Wild, Dummy
  15. from sympy.core.sympify import sympify
  16. from sympy.functions.combinatorial.factorials import factorial
  17. from sympy.functions.elementary.complexes import arg, unpolarify, im, re, Abs
  18. from sympy.functions.elementary.miscellaneous import sqrt
  19. from sympy.ntheory import multiplicity, perfect_power
  20. from sympy.ntheory.factor_ import factorint
  21. # NOTE IMPORTANT
  22. # The series expansion code in this file is an important part of the gruntz
  23. # algorithm for determining limits. _eval_nseries has to return a generalized
  24. # power series with coefficients in C(log(x), log).
  25. # In more detail, the result of _eval_nseries(self, x, n) must be
  26. # c_0*x**e_0 + ... (finitely many terms)
  27. # where e_i are numbers (not necessarily integers) and c_i involve only
  28. # numbers, the function log, and log(x). [This also means it must not contain
  29. # log(x(1+p)), this *has* to be expanded to log(x)+log(1+p) if x.is_positive and
  30. # p.is_positive.]
  31. class ExpBase(Function):
  32. unbranched = True
  33. _singularities = (S.ComplexInfinity,)
  34. @property
  35. def kind(self):
  36. return self.exp.kind
  37. def inverse(self, argindex=1):
  38. """
  39. Returns the inverse function of ``exp(x)``.
  40. """
  41. return log
  42. def as_numer_denom(self):
  43. """
  44. Returns this with a positive exponent as a 2-tuple (a fraction).
  45. Examples
  46. ========
  47. >>> from sympy import exp
  48. >>> from sympy.abc import x
  49. >>> exp(-x).as_numer_denom()
  50. (1, exp(x))
  51. >>> exp(x).as_numer_denom()
  52. (exp(x), 1)
  53. """
  54. # this should be the same as Pow.as_numer_denom wrt
  55. # exponent handling
  56. exp = self.exp
  57. neg_exp = exp.is_negative
  58. if not neg_exp and not (-exp).is_negative:
  59. neg_exp = exp.could_extract_minus_sign()
  60. if neg_exp:
  61. return S.One, self.func(-exp)
  62. return self, S.One
  63. @property
  64. def exp(self):
  65. """
  66. Returns the exponent of the function.
  67. """
  68. return self.args[0]
  69. def as_base_exp(self):
  70. """
  71. Returns the 2-tuple (base, exponent).
  72. """
  73. return self.func(1), Mul(*self.args)
  74. def _eval_adjoint(self):
  75. return self.func(self.exp.adjoint())
  76. def _eval_conjugate(self):
  77. return self.func(self.exp.conjugate())
  78. def _eval_transpose(self):
  79. return self.func(self.exp.transpose())
  80. def _eval_is_finite(self):
  81. arg = self.exp
  82. if arg.is_infinite:
  83. if arg.is_extended_negative:
  84. return True
  85. if arg.is_extended_positive:
  86. return False
  87. if arg.is_finite:
  88. return True
  89. def _eval_is_rational(self):
  90. s = self.func(*self.args)
  91. if s.func == self.func:
  92. z = s.exp.is_zero
  93. if z:
  94. return True
  95. elif s.exp.is_rational and fuzzy_not(z):
  96. return False
  97. else:
  98. return s.is_rational
  99. def _eval_is_zero(self):
  100. return self.exp is S.NegativeInfinity
  101. def _eval_power(self, other):
  102. """exp(arg)**e -> exp(arg*e) if assumptions allow it.
  103. """
  104. b, e = self.as_base_exp()
  105. return Pow._eval_power(Pow(b, e, evaluate=False), other)
  106. def _eval_expand_power_exp(self, **hints):
  107. from sympy.concrete.products import Product
  108. from sympy.concrete.summations import Sum
  109. arg = self.args[0]
  110. if arg.is_Add and arg.is_commutative:
  111. return Mul.fromiter(self.func(x) for x in arg.args)
  112. elif isinstance(arg, Sum) and arg.is_commutative:
  113. return Product(self.func(arg.function), *arg.limits)
  114. return self.func(arg)
  115. class exp_polar(ExpBase):
  116. r"""
  117. Represent a *polar number* (see g-function Sphinx documentation).
  118. Explanation
  119. ===========
  120. ``exp_polar`` represents the function
  121. `Exp: \mathbb{C} \rightarrow \mathcal{S}`, sending the complex number
  122. `z = a + bi` to the polar number `r = exp(a), \theta = b`. It is one of
  123. the main functions to construct polar numbers.
  124. Examples
  125. ========
  126. >>> from sympy import exp_polar, pi, I, exp
  127. The main difference is that polar numbers do not "wrap around" at `2 \pi`:
  128. >>> exp(2*pi*I)
  129. 1
  130. >>> exp_polar(2*pi*I)
  131. exp_polar(2*I*pi)
  132. apart from that they behave mostly like classical complex numbers:
  133. >>> exp_polar(2)*exp_polar(3)
  134. exp_polar(5)
  135. See Also
  136. ========
  137. sympy.simplify.powsimp.powsimp
  138. polar_lift
  139. periodic_argument
  140. principal_branch
  141. """
  142. is_polar = True
  143. is_comparable = False # cannot be evalf'd
  144. def _eval_Abs(self): # Abs is never a polar number
  145. return exp(re(self.args[0]))
  146. def _eval_evalf(self, prec):
  147. """ Careful! any evalf of polar numbers is flaky """
  148. i = im(self.args[0])
  149. try:
  150. bad = (i <= -pi or i > pi)
  151. except TypeError:
  152. bad = True
  153. if bad:
  154. return self # cannot evalf for this argument
  155. res = exp(self.args[0])._eval_evalf(prec)
  156. if i > 0 and im(res) < 0:
  157. # i ~ pi, but exp(I*i) evaluated to argument slightly bigger than pi
  158. return re(res)
  159. return res
  160. def _eval_power(self, other):
  161. return self.func(self.args[0]*other)
  162. def _eval_is_extended_real(self):
  163. if self.args[0].is_extended_real:
  164. return True
  165. def as_base_exp(self):
  166. # XXX exp_polar(0) is special!
  167. if self.args[0] == 0:
  168. return self, S.One
  169. return ExpBase.as_base_exp(self)
  170. class ExpMeta(FunctionClass):
  171. def __instancecheck__(cls, instance):
  172. if exp in instance.__class__.__mro__:
  173. return True
  174. return isinstance(instance, Pow) and instance.base is S.Exp1
  175. class exp(ExpBase, metaclass=ExpMeta):
  176. """
  177. The exponential function, :math:`e^x`.
  178. Examples
  179. ========
  180. >>> from sympy import exp, I, pi
  181. >>> from sympy.abc import x
  182. >>> exp(x)
  183. exp(x)
  184. >>> exp(x).diff(x)
  185. exp(x)
  186. >>> exp(I*pi)
  187. -1
  188. Parameters
  189. ==========
  190. arg : Expr
  191. See Also
  192. ========
  193. log
  194. """
  195. def fdiff(self, argindex=1):
  196. """
  197. Returns the first derivative of this function.
  198. """
  199. if argindex == 1:
  200. return self
  201. else:
  202. raise ArgumentIndexError(self, argindex)
  203. def _eval_refine(self, assumptions):
  204. from sympy.assumptions import ask, Q
  205. arg = self.args[0]
  206. if arg.is_Mul:
  207. Ioo = I*S.Infinity
  208. if arg in [Ioo, -Ioo]:
  209. return S.NaN
  210. coeff = arg.as_coefficient(pi*I)
  211. if coeff:
  212. if ask(Q.integer(2*coeff)):
  213. if ask(Q.even(coeff)):
  214. return S.One
  215. elif ask(Q.odd(coeff)):
  216. return S.NegativeOne
  217. elif ask(Q.even(coeff + S.Half)):
  218. return -I
  219. elif ask(Q.odd(coeff + S.Half)):
  220. return I
  221. @classmethod
  222. def eval(cls, arg):
  223. from sympy.calculus import AccumBounds
  224. from sympy.matrices.matrices import MatrixBase
  225. from sympy.sets.setexpr import SetExpr
  226. from sympy.simplify.simplify import logcombine
  227. if isinstance(arg, MatrixBase):
  228. return arg.exp()
  229. elif global_parameters.exp_is_pow:
  230. return Pow(S.Exp1, arg)
  231. elif arg.is_Number:
  232. if arg is S.NaN:
  233. return S.NaN
  234. elif arg.is_zero:
  235. return S.One
  236. elif arg is S.One:
  237. return S.Exp1
  238. elif arg is S.Infinity:
  239. return S.Infinity
  240. elif arg is S.NegativeInfinity:
  241. return S.Zero
  242. elif arg is S.ComplexInfinity:
  243. return S.NaN
  244. elif isinstance(arg, log):
  245. return arg.args[0]
  246. elif isinstance(arg, AccumBounds):
  247. return AccumBounds(exp(arg.min), exp(arg.max))
  248. elif isinstance(arg, SetExpr):
  249. return arg._eval_func(cls)
  250. elif arg.is_Mul:
  251. coeff = arg.as_coefficient(pi*I)
  252. if coeff:
  253. if (2*coeff).is_integer:
  254. if coeff.is_even:
  255. return S.One
  256. elif coeff.is_odd:
  257. return S.NegativeOne
  258. elif (coeff + S.Half).is_even:
  259. return -I
  260. elif (coeff + S.Half).is_odd:
  261. return I
  262. elif coeff.is_Rational:
  263. ncoeff = coeff % 2 # restrict to [0, 2pi)
  264. if ncoeff > 1: # restrict to (-pi, pi]
  265. ncoeff -= 2
  266. if ncoeff != coeff:
  267. return cls(ncoeff*pi*I)
  268. # Warning: code in risch.py will be very sensitive to changes
  269. # in this (see DifferentialExtension).
  270. # look for a single log factor
  271. coeff, terms = arg.as_coeff_Mul()
  272. # but it can't be multiplied by oo
  273. if coeff in [S.NegativeInfinity, S.Infinity]:
  274. if terms.is_number:
  275. if coeff is S.NegativeInfinity:
  276. terms = -terms
  277. if re(terms).is_zero and terms is not S.Zero:
  278. return S.NaN
  279. if re(terms).is_positive and im(terms) is not S.Zero:
  280. return S.ComplexInfinity
  281. if re(terms).is_negative:
  282. return S.Zero
  283. return None
  284. coeffs, log_term = [coeff], None
  285. for term in Mul.make_args(terms):
  286. term_ = logcombine(term)
  287. if isinstance(term_, log):
  288. if log_term is None:
  289. log_term = term_.args[0]
  290. else:
  291. return None
  292. elif term.is_comparable:
  293. coeffs.append(term)
  294. else:
  295. return None
  296. return log_term**Mul(*coeffs) if log_term else None
  297. elif arg.is_Add:
  298. out = []
  299. add = []
  300. argchanged = False
  301. for a in arg.args:
  302. if a is S.One:
  303. add.append(a)
  304. continue
  305. newa = cls(a)
  306. if isinstance(newa, cls):
  307. if newa.args[0] != a:
  308. add.append(newa.args[0])
  309. argchanged = True
  310. else:
  311. add.append(a)
  312. else:
  313. out.append(newa)
  314. if out or argchanged:
  315. return Mul(*out)*cls(Add(*add), evaluate=False)
  316. if arg.is_zero:
  317. return S.One
  318. @property
  319. def base(self):
  320. """
  321. Returns the base of the exponential function.
  322. """
  323. return S.Exp1
  324. @staticmethod
  325. @cacheit
  326. def taylor_term(n, x, *previous_terms):
  327. """
  328. Calculates the next term in the Taylor series expansion.
  329. """
  330. if n < 0:
  331. return S.Zero
  332. if n == 0:
  333. return S.One
  334. x = sympify(x)
  335. if previous_terms:
  336. p = previous_terms[-1]
  337. if p is not None:
  338. return p * x / n
  339. return x**n/factorial(n)
  340. def as_real_imag(self, deep=True, **hints):
  341. """
  342. Returns this function as a 2-tuple representing a complex number.
  343. Examples
  344. ========
  345. >>> from sympy import exp, I
  346. >>> from sympy.abc import x
  347. >>> exp(x).as_real_imag()
  348. (exp(re(x))*cos(im(x)), exp(re(x))*sin(im(x)))
  349. >>> exp(1).as_real_imag()
  350. (E, 0)
  351. >>> exp(I).as_real_imag()
  352. (cos(1), sin(1))
  353. >>> exp(1+I).as_real_imag()
  354. (E*cos(1), E*sin(1))
  355. See Also
  356. ========
  357. sympy.functions.elementary.complexes.re
  358. sympy.functions.elementary.complexes.im
  359. """
  360. from sympy.functions.elementary.trigonometric import cos, sin
  361. re, im = self.args[0].as_real_imag()
  362. if deep:
  363. re = re.expand(deep, **hints)
  364. im = im.expand(deep, **hints)
  365. cos, sin = cos(im), sin(im)
  366. return (exp(re)*cos, exp(re)*sin)
  367. def _eval_subs(self, old, new):
  368. # keep processing of power-like args centralized in Pow
  369. if old.is_Pow: # handle (exp(3*log(x))).subs(x**2, z) -> z**(3/2)
  370. old = exp(old.exp*log(old.base))
  371. elif old is S.Exp1 and new.is_Function:
  372. old = exp
  373. if isinstance(old, exp) or old is S.Exp1:
  374. f = lambda a: Pow(*a.as_base_exp(), evaluate=False) if (
  375. a.is_Pow or isinstance(a, exp)) else a
  376. return Pow._eval_subs(f(self), f(old), new)
  377. if old is exp and not new.is_Function:
  378. return new**self.exp._subs(old, new)
  379. return Function._eval_subs(self, old, new)
  380. def _eval_is_extended_real(self):
  381. if self.args[0].is_extended_real:
  382. return True
  383. elif self.args[0].is_imaginary:
  384. arg2 = -S(2) * I * self.args[0] / pi
  385. return arg2.is_even
  386. def _eval_is_complex(self):
  387. def complex_extended_negative(arg):
  388. yield arg.is_complex
  389. yield arg.is_extended_negative
  390. return fuzzy_or(complex_extended_negative(self.args[0]))
  391. def _eval_is_algebraic(self):
  392. if (self.exp / pi / I).is_rational:
  393. return True
  394. if fuzzy_not(self.exp.is_zero):
  395. if self.exp.is_algebraic:
  396. return False
  397. elif (self.exp / pi).is_rational:
  398. return False
  399. def _eval_is_extended_positive(self):
  400. if self.exp.is_extended_real:
  401. return self.args[0] is not S.NegativeInfinity
  402. elif self.exp.is_imaginary:
  403. arg2 = -I * self.args[0] / pi
  404. return arg2.is_even
  405. def _eval_nseries(self, x, n, logx, cdir=0):
  406. # NOTE Please see the comment at the beginning of this file, labelled
  407. # IMPORTANT.
  408. from sympy.functions.elementary.complexes import sign
  409. from sympy.functions.elementary.integers import ceiling
  410. from sympy.series.limits import limit
  411. from sympy.series.order import Order
  412. from sympy.simplify.powsimp import powsimp
  413. arg = self.exp
  414. arg_series = arg._eval_nseries(x, n=n, logx=logx)
  415. if arg_series.is_Order:
  416. return 1 + arg_series
  417. arg0 = limit(arg_series.removeO(), x, 0)
  418. if arg0 is S.NegativeInfinity:
  419. return Order(x**n, x)
  420. if arg0 is S.Infinity:
  421. return self
  422. # checking for indecisiveness/ sign terms in arg0
  423. if any(isinstance(arg, (sign, ImaginaryUnit)) for arg in arg0.args):
  424. return self
  425. t = Dummy("t")
  426. nterms = n
  427. try:
  428. cf = Order(arg.as_leading_term(x, logx=logx), x).getn()
  429. except (NotImplementedError, PoleError):
  430. cf = 0
  431. if cf and cf > 0:
  432. nterms = ceiling(n/cf)
  433. exp_series = exp(t)._taylor(t, nterms)
  434. r = exp(arg0)*exp_series.subs(t, arg_series - arg0)
  435. rep = {logx: log(x)} if logx is not None else {}
  436. if r.subs(rep) == self:
  437. return r
  438. if cf and cf > 1:
  439. r += Order((arg_series - arg0)**n, x)/x**((cf-1)*n)
  440. else:
  441. r += Order((arg_series - arg0)**n, x)
  442. r = r.expand()
  443. r = powsimp(r, deep=True, combine='exp')
  444. # powsimp may introduce unexpanded (-1)**Rational; see PR #17201
  445. simplerat = lambda x: x.is_Rational and x.q in [3, 4, 6]
  446. w = Wild('w', properties=[simplerat])
  447. r = r.replace(S.NegativeOne**w, expand_complex(S.NegativeOne**w))
  448. return r
  449. def _taylor(self, x, n):
  450. l = []
  451. g = None
  452. for i in range(n):
  453. g = self.taylor_term(i, self.args[0], g)
  454. g = g.nseries(x, n=n)
  455. l.append(g.removeO())
  456. return Add(*l)
  457. def _eval_as_leading_term(self, x, logx=None, cdir=0):
  458. from sympy.calculus.util import AccumBounds
  459. arg = self.args[0].cancel().as_leading_term(x, logx=logx)
  460. arg0 = arg.subs(x, 0)
  461. if arg is S.NaN:
  462. return S.NaN
  463. if isinstance(arg0, AccumBounds):
  464. # This check addresses a corner case involving AccumBounds.
  465. # if isinstance(arg, AccumBounds) is True, then arg0 can either be 0,
  466. # AccumBounds(-oo, 0) or AccumBounds(-oo, oo).
  467. # Check out function: test_issue_18473() in test_exponential.py and
  468. # test_limits.py for more information.
  469. if re(cdir) < S.Zero:
  470. return exp(-arg0)
  471. return exp(arg0)
  472. if arg0 is S.NaN:
  473. arg0 = arg.limit(x, 0)
  474. if arg0.is_infinite is False:
  475. return exp(arg0)
  476. raise PoleError("Cannot expand %s around 0" % (self))
  477. def _eval_rewrite_as_sin(self, arg, **kwargs):
  478. from sympy.functions.elementary.trigonometric import sin
  479. return sin(I*arg + pi/2) - I*sin(I*arg)
  480. def _eval_rewrite_as_cos(self, arg, **kwargs):
  481. from sympy.functions.elementary.trigonometric import cos
  482. return cos(I*arg) + I*cos(I*arg + pi/2)
  483. def _eval_rewrite_as_tanh(self, arg, **kwargs):
  484. from sympy.functions.elementary.hyperbolic import tanh
  485. return (1 + tanh(arg/2))/(1 - tanh(arg/2))
  486. def _eval_rewrite_as_sqrt(self, arg, **kwargs):
  487. from sympy.functions.elementary.trigonometric import sin, cos
  488. if arg.is_Mul:
  489. coeff = arg.coeff(pi*I)
  490. if coeff and coeff.is_number:
  491. cosine, sine = cos(pi*coeff), sin(pi*coeff)
  492. if not isinstance(cosine, cos) and not isinstance (sine, sin):
  493. return cosine + I*sine
  494. def _eval_rewrite_as_Pow(self, arg, **kwargs):
  495. if arg.is_Mul:
  496. logs = [a for a in arg.args if isinstance(a, log) and len(a.args) == 1]
  497. if logs:
  498. return Pow(logs[0].args[0], arg.coeff(logs[0]))
  499. def match_real_imag(expr):
  500. r"""
  501. Try to match expr with $a + Ib$ for real $a$ and $b$.
  502. ``match_real_imag`` returns a tuple containing the real and imaginary
  503. parts of expr or ``(None, None)`` if direct matching is not possible. Contrary
  504. to :func:`~.re()`, :func:`~.im()``, and ``as_real_imag()``, this helper will not force things
  505. by returning expressions themselves containing ``re()`` or ``im()`` and it
  506. does not expand its argument either.
  507. """
  508. r_, i_ = expr.as_independent(I, as_Add=True)
  509. if i_ == 0 and r_.is_real:
  510. return (r_, i_)
  511. i_ = i_.as_coefficient(I)
  512. if i_ and i_.is_real and r_.is_real:
  513. return (r_, i_)
  514. else:
  515. return (None, None) # simpler to check for than None
  516. class log(Function):
  517. r"""
  518. The natural logarithm function `\ln(x)` or `\log(x)`.
  519. Explanation
  520. ===========
  521. Logarithms are taken with the natural base, `e`. To get
  522. a logarithm of a different base ``b``, use ``log(x, b)``,
  523. which is essentially short-hand for ``log(x)/log(b)``.
  524. ``log`` represents the principal branch of the natural
  525. logarithm. As such it has a branch cut along the negative
  526. real axis and returns values having a complex argument in
  527. `(-\pi, \pi]`.
  528. Examples
  529. ========
  530. >>> from sympy import log, sqrt, S, I
  531. >>> log(8, 2)
  532. 3
  533. >>> log(S(8)/3, 2)
  534. -log(3)/log(2) + 3
  535. >>> log(-1 + I*sqrt(3))
  536. log(2) + 2*I*pi/3
  537. See Also
  538. ========
  539. exp
  540. """
  541. args: tTuple[Expr]
  542. _singularities = (S.Zero, S.ComplexInfinity)
  543. def fdiff(self, argindex=1):
  544. """
  545. Returns the first derivative of the function.
  546. """
  547. if argindex == 1:
  548. return 1/self.args[0]
  549. else:
  550. raise ArgumentIndexError(self, argindex)
  551. def inverse(self, argindex=1):
  552. r"""
  553. Returns `e^x`, the inverse function of `\log(x)`.
  554. """
  555. return exp
  556. @classmethod
  557. def eval(cls, arg, base=None):
  558. from sympy.calculus import AccumBounds
  559. from sympy.sets.setexpr import SetExpr
  560. arg = sympify(arg)
  561. if base is not None:
  562. base = sympify(base)
  563. if base == 1:
  564. if arg == 1:
  565. return S.NaN
  566. else:
  567. return S.ComplexInfinity
  568. try:
  569. # handle extraction of powers of the base now
  570. # or else expand_log in Mul would have to handle this
  571. n = multiplicity(base, arg)
  572. if n:
  573. return n + log(arg / base**n) / log(base)
  574. else:
  575. return log(arg)/log(base)
  576. except ValueError:
  577. pass
  578. if base is not S.Exp1:
  579. return cls(arg)/cls(base)
  580. else:
  581. return cls(arg)
  582. if arg.is_Number:
  583. if arg.is_zero:
  584. return S.ComplexInfinity
  585. elif arg is S.One:
  586. return S.Zero
  587. elif arg is S.Infinity:
  588. return S.Infinity
  589. elif arg is S.NegativeInfinity:
  590. return S.Infinity
  591. elif arg is S.NaN:
  592. return S.NaN
  593. elif arg.is_Rational and arg.p == 1:
  594. return -cls(arg.q)
  595. if arg.is_Pow and arg.base is S.Exp1 and arg.exp.is_extended_real:
  596. return arg.exp
  597. if isinstance(arg, exp) and arg.exp.is_extended_real:
  598. return arg.exp
  599. elif isinstance(arg, exp) and arg.exp.is_number:
  600. r_, i_ = match_real_imag(arg.exp)
  601. if i_ and i_.is_comparable:
  602. i_ %= 2*pi
  603. if i_ > pi:
  604. i_ -= 2*pi
  605. return r_ + expand_mul(i_ * I, deep=False)
  606. elif isinstance(arg, exp_polar):
  607. return unpolarify(arg.exp)
  608. elif isinstance(arg, AccumBounds):
  609. if arg.min.is_positive:
  610. return AccumBounds(log(arg.min), log(arg.max))
  611. elif arg.min.is_zero:
  612. return AccumBounds(S.NegativeInfinity, log(arg.max))
  613. else:
  614. return S.NaN
  615. elif isinstance(arg, SetExpr):
  616. return arg._eval_func(cls)
  617. if arg.is_number:
  618. if arg.is_negative:
  619. return pi * I + cls(-arg)
  620. elif arg is S.ComplexInfinity:
  621. return S.ComplexInfinity
  622. elif arg is S.Exp1:
  623. return S.One
  624. if arg.is_zero:
  625. return S.ComplexInfinity
  626. # don't autoexpand Pow or Mul (see the issue 3351):
  627. if not arg.is_Add:
  628. coeff = arg.as_coefficient(I)
  629. if coeff is not None:
  630. if coeff is S.Infinity:
  631. return S.Infinity
  632. elif coeff is S.NegativeInfinity:
  633. return S.Infinity
  634. elif coeff.is_Rational:
  635. if coeff.is_nonnegative:
  636. return pi * I * S.Half + cls(coeff)
  637. else:
  638. return -pi * I * S.Half + cls(-coeff)
  639. if arg.is_number and arg.is_algebraic:
  640. # Match arg = coeff*(r_ + i_*I) with coeff>0, r_ and i_ real.
  641. coeff, arg_ = arg.as_independent(I, as_Add=False)
  642. if coeff.is_negative:
  643. coeff *= -1
  644. arg_ *= -1
  645. arg_ = expand_mul(arg_, deep=False)
  646. r_, i_ = arg_.as_independent(I, as_Add=True)
  647. i_ = i_.as_coefficient(I)
  648. if coeff.is_real and i_ and i_.is_real and r_.is_real:
  649. if r_.is_zero:
  650. if i_.is_positive:
  651. return pi * I * S.Half + cls(coeff * i_)
  652. elif i_.is_negative:
  653. return -pi * I * S.Half + cls(coeff * -i_)
  654. else:
  655. from sympy.simplify import ratsimp
  656. # Check for arguments involving rational multiples of pi
  657. t = (i_/r_).cancel()
  658. t1 = (-t).cancel()
  659. atan_table = _log_atan_table()
  660. if t in atan_table:
  661. modulus = ratsimp(coeff * Abs(arg_))
  662. if r_.is_positive:
  663. return cls(modulus) + I * atan_table[t]
  664. else:
  665. return cls(modulus) + I * (atan_table[t] - pi)
  666. elif t1 in atan_table:
  667. modulus = ratsimp(coeff * Abs(arg_))
  668. if r_.is_positive:
  669. return cls(modulus) + I * (-atan_table[t1])
  670. else:
  671. return cls(modulus) + I * (pi - atan_table[t1])
  672. def as_base_exp(self):
  673. """
  674. Returns this function in the form (base, exponent).
  675. """
  676. return self, S.One
  677. @staticmethod
  678. @cacheit
  679. def taylor_term(n, x, *previous_terms): # of log(1+x)
  680. r"""
  681. Returns the next term in the Taylor series expansion of `\log(1+x)`.
  682. """
  683. from sympy.simplify.powsimp import powsimp
  684. if n < 0:
  685. return S.Zero
  686. x = sympify(x)
  687. if n == 0:
  688. return x
  689. if previous_terms:
  690. p = previous_terms[-1]
  691. if p is not None:
  692. return powsimp((-n) * p * x / (n + 1), deep=True, combine='exp')
  693. return (1 - 2*(n % 2)) * x**(n + 1)/(n + 1)
  694. def _eval_expand_log(self, deep=True, **hints):
  695. from sympy.concrete import Sum, Product
  696. force = hints.get('force', False)
  697. factor = hints.get('factor', False)
  698. if (len(self.args) == 2):
  699. return expand_log(self.func(*self.args), deep=deep, force=force)
  700. arg = self.args[0]
  701. if arg.is_Integer:
  702. # remove perfect powers
  703. p = perfect_power(arg)
  704. logarg = None
  705. coeff = 1
  706. if p is not False:
  707. arg, coeff = p
  708. logarg = self.func(arg)
  709. # expand as product of its prime factors if factor=True
  710. if factor:
  711. p = factorint(arg)
  712. if arg not in p.keys():
  713. logarg = sum(n*log(val) for val, n in p.items())
  714. if logarg is not None:
  715. return coeff*logarg
  716. elif arg.is_Rational:
  717. return log(arg.p) - log(arg.q)
  718. elif arg.is_Mul:
  719. expr = []
  720. nonpos = []
  721. for x in arg.args:
  722. if force or x.is_positive or x.is_polar:
  723. a = self.func(x)
  724. if isinstance(a, log):
  725. expr.append(self.func(x)._eval_expand_log(**hints))
  726. else:
  727. expr.append(a)
  728. elif x.is_negative:
  729. a = self.func(-x)
  730. expr.append(a)
  731. nonpos.append(S.NegativeOne)
  732. else:
  733. nonpos.append(x)
  734. return Add(*expr) + log(Mul(*nonpos))
  735. elif arg.is_Pow or isinstance(arg, exp):
  736. if force or (arg.exp.is_extended_real and (arg.base.is_positive or ((arg.exp+1)
  737. .is_positive and (arg.exp-1).is_nonpositive))) or arg.base.is_polar:
  738. b = arg.base
  739. e = arg.exp
  740. a = self.func(b)
  741. if isinstance(a, log):
  742. return unpolarify(e) * a._eval_expand_log(**hints)
  743. else:
  744. return unpolarify(e) * a
  745. elif isinstance(arg, Product):
  746. if force or arg.function.is_positive:
  747. return Sum(log(arg.function), *arg.limits)
  748. return self.func(arg)
  749. def _eval_simplify(self, **kwargs):
  750. from sympy.simplify.simplify import expand_log, simplify, inversecombine
  751. if len(self.args) == 2: # it's unevaluated
  752. return simplify(self.func(*self.args), **kwargs)
  753. expr = self.func(simplify(self.args[0], **kwargs))
  754. if kwargs['inverse']:
  755. expr = inversecombine(expr)
  756. expr = expand_log(expr, deep=True)
  757. return min([expr, self], key=kwargs['measure'])
  758. def as_real_imag(self, deep=True, **hints):
  759. """
  760. Returns this function as a complex coordinate.
  761. Examples
  762. ========
  763. >>> from sympy import I, log
  764. >>> from sympy.abc import x
  765. >>> log(x).as_real_imag()
  766. (log(Abs(x)), arg(x))
  767. >>> log(I).as_real_imag()
  768. (0, pi/2)
  769. >>> log(1 + I).as_real_imag()
  770. (log(sqrt(2)), pi/4)
  771. >>> log(I*x).as_real_imag()
  772. (log(Abs(x)), arg(I*x))
  773. """
  774. sarg = self.args[0]
  775. if deep:
  776. sarg = self.args[0].expand(deep, **hints)
  777. sarg_abs = Abs(sarg)
  778. if sarg_abs == sarg:
  779. return self, S.Zero
  780. sarg_arg = arg(sarg)
  781. if hints.get('log', False): # Expand the log
  782. hints['complex'] = False
  783. return (log(sarg_abs).expand(deep, **hints), sarg_arg)
  784. else:
  785. return log(sarg_abs), sarg_arg
  786. def _eval_is_rational(self):
  787. s = self.func(*self.args)
  788. if s.func == self.func:
  789. if (self.args[0] - 1).is_zero:
  790. return True
  791. if s.args[0].is_rational and fuzzy_not((self.args[0] - 1).is_zero):
  792. return False
  793. else:
  794. return s.is_rational
  795. def _eval_is_algebraic(self):
  796. s = self.func(*self.args)
  797. if s.func == self.func:
  798. if (self.args[0] - 1).is_zero:
  799. return True
  800. elif fuzzy_not((self.args[0] - 1).is_zero):
  801. if self.args[0].is_algebraic:
  802. return False
  803. else:
  804. return s.is_algebraic
  805. def _eval_is_extended_real(self):
  806. return self.args[0].is_extended_positive
  807. def _eval_is_complex(self):
  808. z = self.args[0]
  809. return fuzzy_and([z.is_complex, fuzzy_not(z.is_zero)])
  810. def _eval_is_finite(self):
  811. arg = self.args[0]
  812. if arg.is_zero:
  813. return False
  814. return arg.is_finite
  815. def _eval_is_extended_positive(self):
  816. return (self.args[0] - 1).is_extended_positive
  817. def _eval_is_zero(self):
  818. return (self.args[0] - 1).is_zero
  819. def _eval_is_extended_nonnegative(self):
  820. return (self.args[0] - 1).is_extended_nonnegative
  821. def _eval_nseries(self, x, n, logx, cdir=0):
  822. # NOTE Please see the comment at the beginning of this file, labelled
  823. # IMPORTANT.
  824. from sympy.series.order import Order
  825. from sympy.simplify.simplify import logcombine
  826. from sympy.core.symbol import Dummy
  827. if self.args[0] == x:
  828. return log(x) if logx is None else logx
  829. arg = self.args[0]
  830. t = Dummy('t', positive=True)
  831. if cdir == 0:
  832. cdir = 1
  833. z = arg.subs(x, cdir*t)
  834. k, l = Wild("k"), Wild("l")
  835. r = z.match(k*t**l)
  836. if r is not None:
  837. k, l = r[k], r[l]
  838. if l != 0 and not l.has(t) and not k.has(t):
  839. r = l*log(x) if logx is None else l*logx
  840. r += log(k) - l*log(cdir) # XXX true regardless of assumptions?
  841. return r
  842. def coeff_exp(term, x):
  843. coeff, exp = S.One, S.Zero
  844. for factor in Mul.make_args(term):
  845. if factor.has(x):
  846. base, exp = factor.as_base_exp()
  847. if base != x:
  848. try:
  849. return term.leadterm(x)
  850. except ValueError:
  851. return term, S.Zero
  852. else:
  853. coeff *= factor
  854. return coeff, exp
  855. # TODO new and probably slow
  856. try:
  857. a, b = z.leadterm(t, logx=logx, cdir=1)
  858. except (ValueError, NotImplementedError, PoleError):
  859. s = z._eval_nseries(t, n=n, logx=logx, cdir=1)
  860. while s.is_Order:
  861. n += 1
  862. s = z._eval_nseries(t, n=n, logx=logx, cdir=1)
  863. try:
  864. a, b = s.removeO().leadterm(t, cdir=1)
  865. except ValueError:
  866. a, b = s.removeO().as_leading_term(t, cdir=1), S.Zero
  867. p = (z/(a*t**b) - 1)._eval_nseries(t, n=n, logx=logx, cdir=1)
  868. if p.has(exp):
  869. p = logcombine(p)
  870. if isinstance(p, Order):
  871. n = p.getn()
  872. _, d = coeff_exp(p, t)
  873. logx = log(x) if logx is None else logx
  874. if not d.is_positive:
  875. res = log(a) - b*log(cdir) + b*logx
  876. _res = res
  877. logflags = {"deep": True, "log": True, "mul": False, "power_exp": False,
  878. "power_base": False, "multinomial": False, "basic": False, "force": True,
  879. "factor": False}
  880. expr = self.expand(**logflags)
  881. if (not a.could_extract_minus_sign() and
  882. logx.could_extract_minus_sign()):
  883. _res = _res.subs(-logx, -log(x)).expand(**logflags)
  884. else:
  885. _res = _res.subs(logx, log(x)).expand(**logflags)
  886. if _res == expr:
  887. return res
  888. return res + Order(x**n, x)
  889. def mul(d1, d2):
  890. res = {}
  891. for e1, e2 in product(d1, d2):
  892. ex = e1 + e2
  893. if ex < n:
  894. res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
  895. return res
  896. pterms = {}
  897. for term in Add.make_args(p.removeO()):
  898. co1, e1 = coeff_exp(term, t)
  899. pterms[e1] = pterms.get(e1, S.Zero) + co1
  900. k = S.One
  901. terms = {}
  902. pk = pterms
  903. while k*d < n:
  904. coeff = -S.NegativeOne**k/k
  905. for ex in pk:
  906. _ = terms.get(ex, S.Zero) + coeff*pk[ex]
  907. terms[ex] = _.nsimplify()
  908. pk = mul(pk, pterms)
  909. k += S.One
  910. res = log(a) - b*log(cdir) + b*logx
  911. for ex in terms:
  912. res += terms[ex]*t**(ex)
  913. if a.is_negative and im(z) != 0:
  914. from sympy.functions.special.delta_functions import Heaviside
  915. for i, term in enumerate(z.lseries(t)):
  916. if not term.is_real or i == 5:
  917. break
  918. if i < 5:
  919. coeff, _ = term.as_coeff_exponent(t)
  920. res += -2*I*pi*Heaviside(-im(coeff), 0)
  921. res = res.subs(t, x/cdir)
  922. return res + Order(x**n, x)
  923. def _eval_as_leading_term(self, x, logx=None, cdir=0):
  924. # NOTE
  925. # Refer https://github.com/sympy/sympy/pull/23592 for more information
  926. # on each of the following steps involved in this method.
  927. arg0 = self.args[0].together()
  928. # STEP 1
  929. t = Dummy('t', positive=True)
  930. if cdir == 0:
  931. cdir = 1
  932. z = arg0.subs(x, cdir*t)
  933. # STEP 2
  934. try:
  935. c, e = z.leadterm(t, logx=logx, cdir=1)
  936. except ValueError:
  937. arg = arg0.as_leading_term(x, logx=logx, cdir=cdir)
  938. return log(arg)
  939. if c.has(t):
  940. c = c.subs(t, x/cdir)
  941. if e != 0:
  942. raise PoleError("Cannot expand %s around 0" % (self))
  943. return log(c)
  944. # STEP 3
  945. if c == S.One and e == S.Zero:
  946. return (arg0 - S.One).as_leading_term(x, logx=logx)
  947. # STEP 4
  948. res = log(c) - e*log(cdir)
  949. logx = log(x) if logx is None else logx
  950. res += e*logx
  951. # STEP 5
  952. if c.is_negative and im(z) != 0:
  953. from sympy.functions.special.delta_functions import Heaviside
  954. for i, term in enumerate(z.lseries(t)):
  955. if not term.is_real or i == 5:
  956. break
  957. if i < 5:
  958. coeff, _ = term.as_coeff_exponent(t)
  959. res += -2*I*pi*Heaviside(-im(coeff), 0)
  960. return res
  961. class LambertW(Function):
  962. r"""
  963. The Lambert W function $W(z)$ is defined as the inverse
  964. function of $w \exp(w)$ [1]_.
  965. Explanation
  966. ===========
  967. In other words, the value of $W(z)$ is such that $z = W(z) \exp(W(z))$
  968. for any complex number $z$. The Lambert W function is a multivalued
  969. function with infinitely many branches $W_k(z)$, indexed by
  970. $k \in \mathbb{Z}$. Each branch gives a different solution $w$
  971. of the equation $z = w \exp(w)$.
  972. The Lambert W function has two partially real branches: the
  973. principal branch ($k = 0$) is real for real $z > -1/e$, and the
  974. $k = -1$ branch is real for $-1/e < z < 0$. All branches except
  975. $k = 0$ have a logarithmic singularity at $z = 0$.
  976. Examples
  977. ========
  978. >>> from sympy import LambertW
  979. >>> LambertW(1.2)
  980. 0.635564016364870
  981. >>> LambertW(1.2, -1).n()
  982. -1.34747534407696 - 4.41624341514535*I
  983. >>> LambertW(-1).is_real
  984. False
  985. References
  986. ==========
  987. .. [1] https://en.wikipedia.org/wiki/Lambert_W_function
  988. """
  989. _singularities = (-Pow(S.Exp1, -1, evaluate=False), S.ComplexInfinity)
  990. @classmethod
  991. def eval(cls, x, k=None):
  992. if k == S.Zero:
  993. return cls(x)
  994. elif k is None:
  995. k = S.Zero
  996. if k.is_zero:
  997. if x.is_zero:
  998. return S.Zero
  999. if x is S.Exp1:
  1000. return S.One
  1001. if x == -1/S.Exp1:
  1002. return S.NegativeOne
  1003. if x == -log(2)/2:
  1004. return -log(2)
  1005. if x == 2*log(2):
  1006. return log(2)
  1007. if x == -pi/2:
  1008. return I*pi/2
  1009. if x == exp(1 + S.Exp1):
  1010. return S.Exp1
  1011. if x is S.Infinity:
  1012. return S.Infinity
  1013. if x.is_zero:
  1014. return S.Zero
  1015. if fuzzy_not(k.is_zero):
  1016. if x.is_zero:
  1017. return S.NegativeInfinity
  1018. if k is S.NegativeOne:
  1019. if x == -pi/2:
  1020. return -I*pi/2
  1021. elif x == -1/S.Exp1:
  1022. return S.NegativeOne
  1023. elif x == -2*exp(-2):
  1024. return -Integer(2)
  1025. def fdiff(self, argindex=1):
  1026. """
  1027. Return the first derivative of this function.
  1028. """
  1029. x = self.args[0]
  1030. if len(self.args) == 1:
  1031. if argindex == 1:
  1032. return LambertW(x)/(x*(1 + LambertW(x)))
  1033. else:
  1034. k = self.args[1]
  1035. if argindex == 1:
  1036. return LambertW(x, k)/(x*(1 + LambertW(x, k)))
  1037. raise ArgumentIndexError(self, argindex)
  1038. def _eval_is_extended_real(self):
  1039. x = self.args[0]
  1040. if len(self.args) == 1:
  1041. k = S.Zero
  1042. else:
  1043. k = self.args[1]
  1044. if k.is_zero:
  1045. if (x + 1/S.Exp1).is_positive:
  1046. return True
  1047. elif (x + 1/S.Exp1).is_nonpositive:
  1048. return False
  1049. elif (k + 1).is_zero:
  1050. if x.is_negative and (x + 1/S.Exp1).is_positive:
  1051. return True
  1052. elif x.is_nonpositive or (x + 1/S.Exp1).is_nonnegative:
  1053. return False
  1054. elif fuzzy_not(k.is_zero) and fuzzy_not((k + 1).is_zero):
  1055. if x.is_extended_real:
  1056. return False
  1057. def _eval_is_finite(self):
  1058. return self.args[0].is_finite
  1059. def _eval_is_algebraic(self):
  1060. s = self.func(*self.args)
  1061. if s.func == self.func:
  1062. if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic:
  1063. return False
  1064. else:
  1065. return s.is_algebraic
  1066. def _eval_as_leading_term(self, x, logx=None, cdir=0):
  1067. if len(self.args) == 1:
  1068. arg = self.args[0]
  1069. arg0 = arg.subs(x, 0).cancel()
  1070. if not arg0.is_zero:
  1071. return self.func(arg0)
  1072. return arg.as_leading_term(x)
  1073. def _eval_nseries(self, x, n, logx, cdir=0):
  1074. if len(self.args) == 1:
  1075. from sympy.functions.elementary.integers import ceiling
  1076. from sympy.series.order import Order
  1077. arg = self.args[0].nseries(x, n=n, logx=logx)
  1078. lt = arg.as_leading_term(x, logx=logx)
  1079. lte = 1
  1080. if lt.is_Pow:
  1081. lte = lt.exp
  1082. if ceiling(n/lte) >= 1:
  1083. s = Add(*[(-S.One)**(k - 1)*Integer(k)**(k - 2)/
  1084. factorial(k - 1)*arg**k for k in range(1, ceiling(n/lte))])
  1085. s = expand_multinomial(s)
  1086. else:
  1087. s = S.Zero
  1088. return s + Order(x**n, x)
  1089. return super()._eval_nseries(x, n, logx)
  1090. def _eval_is_zero(self):
  1091. x = self.args[0]
  1092. if len(self.args) == 1:
  1093. return x.is_zero
  1094. else:
  1095. return fuzzy_and([x.is_zero, self.args[1].is_zero])
  1096. @cacheit
  1097. def _log_atan_table():
  1098. return {
  1099. # first quadrant only
  1100. sqrt(3): pi / 3,
  1101. 1: pi / 4,
  1102. sqrt(5 - 2 * sqrt(5)): pi / 5,
  1103. sqrt(2) * sqrt(5 - sqrt(5)) / (1 + sqrt(5)): pi / 5,
  1104. sqrt(5 + 2 * sqrt(5)): pi * Rational(2, 5),
  1105. sqrt(2) * sqrt(sqrt(5) + 5) / (-1 + sqrt(5)): pi * Rational(2, 5),
  1106. sqrt(3) / 3: pi / 6,
  1107. sqrt(2) - 1: pi / 8,
  1108. sqrt(2 - sqrt(2)) / sqrt(sqrt(2) + 2): pi / 8,
  1109. sqrt(2) + 1: pi * Rational(3, 8),
  1110. sqrt(sqrt(2) + 2) / sqrt(2 - sqrt(2)): pi * Rational(3, 8),
  1111. sqrt(1 - 2 * sqrt(5) / 5): pi / 10,
  1112. (-sqrt(2) + sqrt(10)) / (2 * sqrt(sqrt(5) + 5)): pi / 10,
  1113. sqrt(1 + 2 * sqrt(5) / 5): pi * Rational(3, 10),
  1114. (sqrt(2) + sqrt(10)) / (2 * sqrt(5 - sqrt(5))): pi * Rational(3, 10),
  1115. 2 - sqrt(3): pi / 12,
  1116. (-1 + sqrt(3)) / (1 + sqrt(3)): pi / 12,
  1117. 2 + sqrt(3): pi * Rational(5, 12),
  1118. (1 + sqrt(3)) / (-1 + sqrt(3)): pi * Rational(5, 12)
  1119. }