exponential.py 42 KB

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