exponential.py 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218
  1. from typing import Tuple as tTuple
  2. from sympy.core.expr import Expr
  3. from sympy.core import sympify
  4. from sympy.core.add import Add
  5. from sympy.core.cache import cacheit
  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
  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.functions.combinatorial.factorials import factorial
  16. from sympy.functions.elementary.miscellaneous import sqrt
  17. from sympy.ntheory import multiplicity, perfect_power
  18. from sympy.sets.setexpr import SetExpr
  19. # NOTE IMPORTANT
  20. # The series expansion code in this file is an important part of the gruntz
  21. # algorithm for determining limits. _eval_nseries has to return a generalized
  22. # power series with coefficients in C(log(x), log).
  23. # In more detail, the result of _eval_nseries(self, x, n) must be
  24. # c_0*x**e_0 + ... (finitely many terms)
  25. # where e_i are numbers (not necessarily integers) and c_i involve only
  26. # numbers, the function log, and log(x). [This also means it must not contain
  27. # log(x(1+p)), this *has* to be expanded to log(x)+log(1+p) if x.is_positive and
  28. # p.is_positive.]
  29. class ExpBase(Function):
  30. unbranched = True
  31. _singularities = (S.ComplexInfinity,)
  32. @property
  33. def kind(self):
  34. return self.exp.kind
  35. def inverse(self, argindex=1):
  36. """
  37. Returns the inverse function of ``exp(x)``.
  38. """
  39. return log
  40. def as_numer_denom(self):
  41. """
  42. Returns this with a positive exponent as a 2-tuple (a fraction).
  43. Examples
  44. ========
  45. >>> from sympy import exp
  46. >>> from sympy.abc import x
  47. >>> exp(-x).as_numer_denom()
  48. (1, exp(x))
  49. >>> exp(x).as_numer_denom()
  50. (exp(x), 1)
  51. """
  52. # this should be the same as Pow.as_numer_denom wrt
  53. # exponent handling
  54. exp = self.exp
  55. neg_exp = exp.is_negative
  56. if not neg_exp and not (-exp).is_negative:
  57. neg_exp = exp.could_extract_minus_sign()
  58. if neg_exp:
  59. return S.One, self.func(-exp)
  60. return self, S.One
  61. @property
  62. def exp(self):
  63. """
  64. Returns the exponent of the function.
  65. """
  66. return self.args[0]
  67. def as_base_exp(self):
  68. """
  69. Returns the 2-tuple (base, exponent).
  70. """
  71. return self.func(1), Mul(*self.args)
  72. def _eval_adjoint(self):
  73. return self.func(self.exp.adjoint())
  74. def _eval_conjugate(self):
  75. return self.func(self.exp.conjugate())
  76. def _eval_transpose(self):
  77. return self.func(self.exp.transpose())
  78. def _eval_is_finite(self):
  79. arg = self.exp
  80. if arg.is_infinite:
  81. if arg.is_extended_negative:
  82. return True
  83. if arg.is_extended_positive:
  84. return False
  85. if arg.is_finite:
  86. return True
  87. def _eval_is_rational(self):
  88. s = self.func(*self.args)
  89. if s.func == self.func:
  90. z = s.exp.is_zero
  91. if z:
  92. return True
  93. elif s.exp.is_rational and fuzzy_not(z):
  94. return False
  95. else:
  96. return s.is_rational
  97. def _eval_is_zero(self):
  98. return self.exp is S.NegativeInfinity
  99. def _eval_power(self, other):
  100. """exp(arg)**e -> exp(arg*e) if assumptions allow it.
  101. """
  102. b, e = self.as_base_exp()
  103. return Pow._eval_power(Pow(b, e, evaluate=False), other)
  104. def _eval_expand_power_exp(self, **hints):
  105. from sympy.concrete.products import Product
  106. from sympy.concrete.summations import Sum
  107. arg = self.args[0]
  108. if arg.is_Add and arg.is_commutative:
  109. return Mul.fromiter(self.func(x) for x in arg.args)
  110. elif isinstance(arg, Sum) and arg.is_commutative:
  111. return Product(self.func(arg.function), *arg.limits)
  112. return self.func(arg)
  113. class exp_polar(ExpBase):
  114. r"""
  115. Represent a *polar number* (see g-function Sphinx documentation).
  116. Explanation
  117. ===========
  118. ``exp_polar`` represents the function
  119. `Exp: \mathbb{C} \rightarrow \mathcal{S}`, sending the complex number
  120. `z = a + bi` to the polar number `r = exp(a), \theta = b`. It is one of
  121. the main functions to construct polar numbers.
  122. Examples
  123. ========
  124. >>> from sympy import exp_polar, pi, I, exp
  125. The main difference is that polar numbers don't "wrap around" at `2 \pi`:
  126. >>> exp(2*pi*I)
  127. 1
  128. >>> exp_polar(2*pi*I)
  129. exp_polar(2*I*pi)
  130. apart from that they behave mostly like classical complex numbers:
  131. >>> exp_polar(2)*exp_polar(3)
  132. exp_polar(5)
  133. See Also
  134. ========
  135. sympy.simplify.powsimp.powsimp
  136. polar_lift
  137. periodic_argument
  138. principal_branch
  139. """
  140. is_polar = True
  141. is_comparable = False # cannot be evalf'd
  142. def _eval_Abs(self): # Abs is never a polar number
  143. from sympy.functions.elementary.complexes import re
  144. return exp(re(self.args[0]))
  145. def _eval_evalf(self, prec):
  146. """ Careful! any evalf of polar numbers is flaky """
  147. from sympy.functions.elementary.complexes import (im, re)
  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 = S.ImaginaryUnit*S.Infinity
  208. if arg in [Ioo, -Ioo]:
  209. return S.NaN
  210. coeff = arg.as_coefficient(S.Pi*S.ImaginaryUnit)
  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 -S.ImaginaryUnit
  219. elif ask(Q.odd(coeff + S.Half)):
  220. return S.ImaginaryUnit
  221. @classmethod
  222. def eval(cls, arg):
  223. from sympy.calculus import AccumBounds
  224. from sympy.matrices.matrices import MatrixBase
  225. from sympy.functions.elementary.complexes import (im, re)
  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(S.Pi*S.ImaginaryUnit)
  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 -S.ImaginaryUnit
  260. elif (coeff + S.Half).is_odd:
  261. return S.ImaginaryUnit
  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*S.Pi*S.ImaginaryUnit)
  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) * S.ImaginaryUnit * self.args[0] / S.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 / S.Pi / S.ImaginaryUnit).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 / S.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 = -S.ImaginaryUnit * self.args[0] / S.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.integers import ceiling
  409. from sympy.series.limits import limit
  410. from sympy.series.order import Order
  411. from sympy.simplify.powsimp import powsimp
  412. arg = self.exp
  413. arg_series = arg._eval_nseries(x, n=n, logx=logx)
  414. if arg_series.is_Order:
  415. return 1 + arg_series
  416. arg0 = limit(arg_series.removeO(), x, 0)
  417. if arg0 is S.NegativeInfinity:
  418. return Order(x**n, x)
  419. if arg0 is S.Infinity:
  420. return self
  421. t = Dummy("t")
  422. nterms = n
  423. try:
  424. cf = Order(arg.as_leading_term(x, logx=logx), x).getn()
  425. except (NotImplementedError, PoleError):
  426. cf = 0
  427. if cf and cf > 0:
  428. nterms = ceiling(n/cf)
  429. exp_series = exp(t)._taylor(t, nterms)
  430. r = exp(arg0)*exp_series.subs(t, arg_series - arg0)
  431. if cf and cf > 1:
  432. r += Order((arg_series - arg0)**n, x)/x**((cf-1)*n)
  433. else:
  434. r += Order((arg_series - arg0)**n, x)
  435. r = r.expand()
  436. r = powsimp(r, deep=True, combine='exp')
  437. # powsimp may introduce unexpanded (-1)**Rational; see PR #17201
  438. simplerat = lambda x: x.is_Rational and x.q in [3, 4, 6]
  439. w = Wild('w', properties=[simplerat])
  440. r = r.replace(S.NegativeOne**w, expand_complex(S.NegativeOne**w))
  441. return r
  442. def _taylor(self, x, n):
  443. l = []
  444. g = None
  445. for i in range(n):
  446. g = self.taylor_term(i, self.args[0], g)
  447. g = g.nseries(x, n=n)
  448. l.append(g.removeO())
  449. return Add(*l)
  450. def _eval_as_leading_term(self, x, logx=None, cdir=0):
  451. arg = self.args[0].cancel().as_leading_term(x, logx=logx)
  452. arg0 = arg.subs(x, 0)
  453. if arg0 is S.NaN:
  454. arg0 = arg.limit(x, 0)
  455. if arg0.is_infinite is False:
  456. return exp(arg0)
  457. raise PoleError("Cannot expand %s around 0" % (self))
  458. def _eval_rewrite_as_sin(self, arg, **kwargs):
  459. from sympy.functions.elementary.trigonometric import sin
  460. I = S.ImaginaryUnit
  461. return sin(I*arg + S.Pi/2) - I*sin(I*arg)
  462. def _eval_rewrite_as_cos(self, arg, **kwargs):
  463. from sympy.functions.elementary.trigonometric import cos
  464. I = S.ImaginaryUnit
  465. return cos(I*arg) + I*cos(I*arg + S.Pi/2)
  466. def _eval_rewrite_as_tanh(self, arg, **kwargs):
  467. from sympy.functions.elementary.hyperbolic import tanh
  468. return (1 + tanh(arg/2))/(1 - tanh(arg/2))
  469. def _eval_rewrite_as_sqrt(self, arg, **kwargs):
  470. from sympy.functions.elementary.trigonometric import sin, cos
  471. if arg.is_Mul:
  472. coeff = arg.coeff(S.Pi*S.ImaginaryUnit)
  473. if coeff and coeff.is_number:
  474. cosine, sine = cos(S.Pi*coeff), sin(S.Pi*coeff)
  475. if not isinstance(cosine, cos) and not isinstance (sine, sin):
  476. return cosine + S.ImaginaryUnit*sine
  477. def _eval_rewrite_as_Pow(self, arg, **kwargs):
  478. if arg.is_Mul:
  479. logs = [a for a in arg.args if isinstance(a, log) and len(a.args) == 1]
  480. if logs:
  481. return Pow(logs[0].args[0], arg.coeff(logs[0]))
  482. def match_real_imag(expr):
  483. r"""
  484. Try to match expr with $a + Ib$ for real $a$ and $b$.
  485. ``match_real_imag`` returns a tuple containing the real and imaginary
  486. parts of expr or ``(None, None)`` if direct matching is not possible. Contrary
  487. to :func:`~.re()`, :func:`~.im()``, and ``as_real_imag()``, this helper will not force things
  488. by returning expressions themselves containing ``re()`` or ``im()`` and it
  489. does not expand its argument either.
  490. """
  491. r_, i_ = expr.as_independent(S.ImaginaryUnit, as_Add=True)
  492. if i_ == 0 and r_.is_real:
  493. return (r_, i_)
  494. i_ = i_.as_coefficient(S.ImaginaryUnit)
  495. if i_ and i_.is_real and r_.is_real:
  496. return (r_, i_)
  497. else:
  498. return (None, None) # simpler to check for than None
  499. class log(Function):
  500. r"""
  501. The natural logarithm function `\ln(x)` or `\log(x)`.
  502. Explanation
  503. ===========
  504. Logarithms are taken with the natural base, `e`. To get
  505. a logarithm of a different base ``b``, use ``log(x, b)``,
  506. which is essentially short-hand for ``log(x)/log(b)``.
  507. ``log`` represents the principal branch of the natural
  508. logarithm. As such it has a branch cut along the negative
  509. real axis and returns values having a complex argument in
  510. `(-\pi, \pi]`.
  511. Examples
  512. ========
  513. >>> from sympy import log, sqrt, S, I
  514. >>> log(8, 2)
  515. 3
  516. >>> log(S(8)/3, 2)
  517. -log(3)/log(2) + 3
  518. >>> log(-1 + I*sqrt(3))
  519. log(2) + 2*I*pi/3
  520. See Also
  521. ========
  522. exp
  523. """
  524. args: tTuple[Expr]
  525. _singularities = (S.Zero, S.ComplexInfinity)
  526. def fdiff(self, argindex=1):
  527. """
  528. Returns the first derivative of the function.
  529. """
  530. if argindex == 1:
  531. return 1/self.args[0]
  532. else:
  533. raise ArgumentIndexError(self, argindex)
  534. def inverse(self, argindex=1):
  535. r"""
  536. Returns `e^x`, the inverse function of `\log(x)`.
  537. """
  538. return exp
  539. @classmethod
  540. def eval(cls, arg, base=None):
  541. from sympy.functions.elementary.complexes import unpolarify
  542. from sympy.calculus import AccumBounds
  543. from sympy.functions.elementary.complexes import Abs
  544. arg = sympify(arg)
  545. if base is not None:
  546. base = sympify(base)
  547. if base == 1:
  548. if arg == 1:
  549. return S.NaN
  550. else:
  551. return S.ComplexInfinity
  552. try:
  553. # handle extraction of powers of the base now
  554. # or else expand_log in Mul would have to handle this
  555. n = multiplicity(base, arg)
  556. if n:
  557. return n + log(arg / base**n) / log(base)
  558. else:
  559. return log(arg)/log(base)
  560. except ValueError:
  561. pass
  562. if base is not S.Exp1:
  563. return cls(arg)/cls(base)
  564. else:
  565. return cls(arg)
  566. if arg.is_Number:
  567. if arg.is_zero:
  568. return S.ComplexInfinity
  569. elif arg is S.One:
  570. return S.Zero
  571. elif arg is S.Infinity:
  572. return S.Infinity
  573. elif arg is S.NegativeInfinity:
  574. return S.Infinity
  575. elif arg is S.NaN:
  576. return S.NaN
  577. elif arg.is_Rational and arg.p == 1:
  578. return -cls(arg.q)
  579. if arg.is_Pow and arg.base is S.Exp1 and arg.exp.is_extended_real:
  580. return arg.exp
  581. I = S.ImaginaryUnit
  582. if isinstance(arg, exp) and arg.exp.is_extended_real:
  583. return arg.exp
  584. elif isinstance(arg, exp) and arg.exp.is_number:
  585. r_, i_ = match_real_imag(arg.exp)
  586. if i_ and i_.is_comparable:
  587. i_ %= 2*S.Pi
  588. if i_ > S.Pi:
  589. i_ -= 2*S.Pi
  590. return r_ + expand_mul(i_ * I, deep=False)
  591. elif isinstance(arg, exp_polar):
  592. return unpolarify(arg.exp)
  593. elif isinstance(arg, AccumBounds):
  594. if arg.min.is_positive:
  595. return AccumBounds(log(arg.min), log(arg.max))
  596. else:
  597. return
  598. elif isinstance(arg, SetExpr):
  599. return arg._eval_func(cls)
  600. if arg.is_number:
  601. if arg.is_negative:
  602. return S.Pi * I + cls(-arg)
  603. elif arg is S.ComplexInfinity:
  604. return S.ComplexInfinity
  605. elif arg is S.Exp1:
  606. return S.One
  607. if arg.is_zero:
  608. return S.ComplexInfinity
  609. # don't autoexpand Pow or Mul (see the issue 3351):
  610. if not arg.is_Add:
  611. coeff = arg.as_coefficient(I)
  612. if coeff is not None:
  613. if coeff is S.Infinity:
  614. return S.Infinity
  615. elif coeff is S.NegativeInfinity:
  616. return S.Infinity
  617. elif coeff.is_Rational:
  618. if coeff.is_nonnegative:
  619. return S.Pi * I * S.Half + cls(coeff)
  620. else:
  621. return -S.Pi * I * S.Half + cls(-coeff)
  622. if arg.is_number and arg.is_algebraic:
  623. # Match arg = coeff*(r_ + i_*I) with coeff>0, r_ and i_ real.
  624. coeff, arg_ = arg.as_independent(I, as_Add=False)
  625. if coeff.is_negative:
  626. coeff *= -1
  627. arg_ *= -1
  628. arg_ = expand_mul(arg_, deep=False)
  629. r_, i_ = arg_.as_independent(I, as_Add=True)
  630. i_ = i_.as_coefficient(I)
  631. if coeff.is_real and i_ and i_.is_real and r_.is_real:
  632. if r_.is_zero:
  633. if i_.is_positive:
  634. return S.Pi * I * S.Half + cls(coeff * i_)
  635. elif i_.is_negative:
  636. return -S.Pi * I * S.Half + cls(coeff * -i_)
  637. else:
  638. from sympy.simplify import ratsimp
  639. # Check for arguments involving rational multiples of pi
  640. t = (i_/r_).cancel()
  641. t1 = (-t).cancel()
  642. atan_table = {
  643. # first quadrant only
  644. sqrt(3): S.Pi/3,
  645. 1: S.Pi/4,
  646. sqrt(5 - 2*sqrt(5)): S.Pi/5,
  647. sqrt(2)*sqrt(5 - sqrt(5))/(1 + sqrt(5)): S.Pi/5,
  648. sqrt(5 + 2*sqrt(5)): S.Pi*Rational(2, 5),
  649. sqrt(2)*sqrt(sqrt(5) + 5)/(-1 + sqrt(5)): S.Pi*Rational(2, 5),
  650. sqrt(3)/3: S.Pi/6,
  651. sqrt(2) - 1: S.Pi/8,
  652. sqrt(2 - sqrt(2))/sqrt(sqrt(2) + 2): S.Pi/8,
  653. sqrt(2) + 1: S.Pi*Rational(3, 8),
  654. sqrt(sqrt(2) + 2)/sqrt(2 - sqrt(2)): S.Pi*Rational(3, 8),
  655. sqrt(1 - 2*sqrt(5)/5): S.Pi/10,
  656. (-sqrt(2) + sqrt(10))/(2*sqrt(sqrt(5) + 5)): S.Pi/10,
  657. sqrt(1 + 2*sqrt(5)/5): S.Pi*Rational(3, 10),
  658. (sqrt(2) + sqrt(10))/(2*sqrt(5 - sqrt(5))): S.Pi*Rational(3, 10),
  659. 2 - sqrt(3): S.Pi/12,
  660. (-1 + sqrt(3))/(1 + sqrt(3)): S.Pi/12,
  661. 2 + sqrt(3): S.Pi*Rational(5, 12),
  662. (1 + sqrt(3))/(-1 + sqrt(3)): S.Pi*Rational(5, 12)
  663. }
  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] - S.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 * (S.Pi - atan_table[t1])
  676. def as_base_exp(self):
  677. """
  678. Returns this function in the form (base, exponent).
  679. """
  680. return self, S.One
  681. @staticmethod
  682. @cacheit
  683. def taylor_term(n, x, *previous_terms): # of log(1+x)
  684. r"""
  685. Returns the next term in the Taylor series expansion of `\log(1+x)`.
  686. """
  687. from sympy.simplify.powsimp import powsimp
  688. if n < 0:
  689. return S.Zero
  690. x = sympify(x)
  691. if n == 0:
  692. return x
  693. if previous_terms:
  694. p = previous_terms[-1]
  695. if p is not None:
  696. return powsimp((-n) * p * x / (n + 1), deep=True, combine='exp')
  697. return (1 - 2*(n % 2)) * x**(n + 1)/(n + 1)
  698. def _eval_expand_log(self, deep=True, **hints):
  699. from sympy.functions.elementary.complexes import unpolarify
  700. from sympy.ntheory.factor_ import factorint
  701. from sympy.concrete import Sum, Product
  702. force = hints.get('force', False)
  703. factor = hints.get('factor', False)
  704. if (len(self.args) == 2):
  705. return expand_log(self.func(*self.args), deep=deep, force=force)
  706. arg = self.args[0]
  707. if arg.is_Integer:
  708. # remove perfect powers
  709. p = perfect_power(arg)
  710. logarg = None
  711. coeff = 1
  712. if p is not False:
  713. arg, coeff = p
  714. logarg = self.func(arg)
  715. # expand as product of its prime factors if factor=True
  716. if factor:
  717. p = factorint(arg)
  718. if arg not in p.keys():
  719. logarg = sum(n*log(val) for val, n in p.items())
  720. if logarg is not None:
  721. return coeff*logarg
  722. elif arg.is_Rational:
  723. return log(arg.p) - log(arg.q)
  724. elif arg.is_Mul:
  725. expr = []
  726. nonpos = []
  727. for x in arg.args:
  728. if force or x.is_positive or x.is_polar:
  729. a = self.func(x)
  730. if isinstance(a, log):
  731. expr.append(self.func(x)._eval_expand_log(**hints))
  732. else:
  733. expr.append(a)
  734. elif x.is_negative:
  735. a = self.func(-x)
  736. expr.append(a)
  737. nonpos.append(S.NegativeOne)
  738. else:
  739. nonpos.append(x)
  740. return Add(*expr) + log(Mul(*nonpos))
  741. elif arg.is_Pow or isinstance(arg, exp):
  742. if force or (arg.exp.is_extended_real and (arg.base.is_positive or ((arg.exp+1)
  743. .is_positive and (arg.exp-1).is_nonpositive))) or arg.base.is_polar:
  744. b = arg.base
  745. e = arg.exp
  746. a = self.func(b)
  747. if isinstance(a, log):
  748. return unpolarify(e) * a._eval_expand_log(**hints)
  749. else:
  750. return unpolarify(e) * a
  751. elif isinstance(arg, Product):
  752. if force or arg.function.is_positive:
  753. return Sum(log(arg.function), *arg.limits)
  754. return self.func(arg)
  755. def _eval_simplify(self, **kwargs):
  756. from sympy.simplify.simplify import expand_log, simplify, inversecombine
  757. if len(self.args) == 2: # it's unevaluated
  758. return simplify(self.func(*self.args), **kwargs)
  759. expr = self.func(simplify(self.args[0], **kwargs))
  760. if kwargs['inverse']:
  761. expr = inversecombine(expr)
  762. expr = expand_log(expr, deep=True)
  763. return min([expr, self], key=kwargs['measure'])
  764. def as_real_imag(self, deep=True, **hints):
  765. """
  766. Returns this function as a complex coordinate.
  767. Examples
  768. ========
  769. >>> from sympy import I, log
  770. >>> from sympy.abc import x
  771. >>> log(x).as_real_imag()
  772. (log(Abs(x)), arg(x))
  773. >>> log(I).as_real_imag()
  774. (0, pi/2)
  775. >>> log(1 + I).as_real_imag()
  776. (log(sqrt(2)), pi/4)
  777. >>> log(I*x).as_real_imag()
  778. (log(Abs(x)), arg(I*x))
  779. """
  780. from sympy.functions.elementary.complexes import (Abs, arg)
  781. sarg = self.args[0]
  782. if deep:
  783. sarg = self.args[0].expand(deep, **hints)
  784. abs = Abs(sarg)
  785. if abs == sarg:
  786. return self, S.Zero
  787. arg = arg(sarg)
  788. if hints.get('log', False): # Expand the log
  789. hints['complex'] = False
  790. return (log(abs).expand(deep, **hints), arg)
  791. else:
  792. return log(abs), arg
  793. def _eval_is_rational(self):
  794. s = self.func(*self.args)
  795. if s.func == self.func:
  796. if (self.args[0] - 1).is_zero:
  797. return True
  798. if s.args[0].is_rational and fuzzy_not((self.args[0] - 1).is_zero):
  799. return False
  800. else:
  801. return s.is_rational
  802. def _eval_is_algebraic(self):
  803. s = self.func(*self.args)
  804. if s.func == self.func:
  805. if (self.args[0] - 1).is_zero:
  806. return True
  807. elif fuzzy_not((self.args[0] - 1).is_zero):
  808. if self.args[0].is_algebraic:
  809. return False
  810. else:
  811. return s.is_algebraic
  812. def _eval_is_extended_real(self):
  813. return self.args[0].is_extended_positive
  814. def _eval_is_complex(self):
  815. z = self.args[0]
  816. return fuzzy_and([z.is_complex, fuzzy_not(z.is_zero)])
  817. def _eval_is_finite(self):
  818. arg = self.args[0]
  819. if arg.is_zero:
  820. return False
  821. return arg.is_finite
  822. def _eval_is_extended_positive(self):
  823. return (self.args[0] - 1).is_extended_positive
  824. def _eval_is_zero(self):
  825. return (self.args[0] - 1).is_zero
  826. def _eval_is_extended_nonnegative(self):
  827. return (self.args[0] - 1).is_extended_nonnegative
  828. def _eval_nseries(self, x, n, logx, cdir=0):
  829. # NOTE Please see the comment at the beginning of this file, labelled
  830. # IMPORTANT.
  831. from sympy.functions.elementary.complexes import im
  832. from sympy.polys.polytools import cancel
  833. from sympy.series.order import Order
  834. from sympy.simplify.simplify import logcombine
  835. from itertools import product
  836. if not logx:
  837. logx = log(x)
  838. if self.args[0] == x:
  839. return logx
  840. arg = self.args[0]
  841. k, l = Wild("k"), Wild("l")
  842. r = arg.match(k*x**l)
  843. if r is not None:
  844. k, l = r[k], r[l]
  845. if l != 0 and not l.has(x) and not k.has(x):
  846. r = log(k) + l*logx # XXX true regardless of assumptions?
  847. return r
  848. def coeff_exp(term, x):
  849. coeff, exp = S.One, S.Zero
  850. for factor in Mul.make_args(term):
  851. if factor.has(x):
  852. base, exp = factor.as_base_exp()
  853. if base != x:
  854. try:
  855. return term.leadterm(x)
  856. except ValueError:
  857. return term, S.Zero
  858. else:
  859. coeff *= factor
  860. return coeff, exp
  861. # TODO new and probably slow
  862. try:
  863. a, b = arg.leadterm(x)
  864. s = arg.nseries(x, n=n+b, logx=logx)
  865. except (ValueError, NotImplementedError, PoleError):
  866. s = arg.nseries(x, n=n, logx=logx)
  867. while s.is_Order:
  868. n += 1
  869. s = arg.nseries(x, n=n, logx=logx)
  870. a, b = s.removeO().leadterm(x)
  871. p = cancel(s/(a*x**b) - 1).expand().powsimp()
  872. if p.has(exp):
  873. p = logcombine(p)
  874. if isinstance(p, Order):
  875. n = p.getn()
  876. _, d = coeff_exp(p, x)
  877. if not d.is_positive:
  878. return log(a) + b*logx + Order(x**n, x)
  879. def mul(d1, d2):
  880. res = {}
  881. for e1, e2 in product(d1, d2):
  882. ex = e1 + e2
  883. if ex < n:
  884. res[ex] = res.get(ex, S.Zero) + d1[e1]*d2[e2]
  885. return res
  886. pterms = {}
  887. for term in Add.make_args(p):
  888. co1, e1 = coeff_exp(term, x)
  889. pterms[e1] = pterms.get(e1, S.Zero) + co1.removeO()
  890. k = S.One
  891. terms = {}
  892. pk = pterms
  893. while k*d < n:
  894. coeff = -S.NegativeOne**k/k
  895. for ex in pk:
  896. terms[ex] = terms.get(ex, S.Zero) + coeff*pk[ex]
  897. pk = mul(pk, pterms)
  898. k += S.One
  899. res = log(a) + b*logx
  900. for ex in terms:
  901. res += terms[ex]*x**(ex)
  902. if cdir != 0:
  903. cdir = self.args[0].dir(x, cdir)
  904. if a.is_real and a.is_negative and im(cdir) < 0:
  905. res -= 2*I*S.Pi
  906. return res + Order(x**n, x)
  907. def _eval_as_leading_term(self, x, logx=None, cdir=0):
  908. from sympy.functions.elementary.complexes import (im, re)
  909. arg0 = self.args[0].together()
  910. arg = arg0.as_leading_term(x, cdir=cdir)
  911. x0 = arg0.subs(x, 0)
  912. if (x0 is S.NaN and logx is None):
  913. x0 = arg.limit(x, 0, dir='-' if re(cdir).is_negative else '+')
  914. if x0 in (S.NegativeInfinity, S.Infinity):
  915. raise PoleError("Cannot expand %s around 0" % (self))
  916. if x0 == 1:
  917. return (arg0 - S.One).as_leading_term(x)
  918. if cdir != 0:
  919. cdir = arg0.dir(x, cdir)
  920. if x0.is_real and x0.is_negative and im(cdir).is_negative:
  921. return self.func(x0) - 2*I*S.Pi
  922. return self.func(arg)
  923. class LambertW(Function):
  924. r"""
  925. The Lambert W function $W(z)$ is defined as the inverse
  926. function of $w \exp(w)$ [1]_.
  927. Explanation
  928. ===========
  929. In other words, the value of $W(z)$ is such that $z = W(z) \exp(W(z))$
  930. for any complex number $z$. The Lambert W function is a multivalued
  931. function with infinitely many branches $W_k(z)$, indexed by
  932. $k \in \mathbb{Z}$. Each branch gives a different solution $w$
  933. of the equation $z = w \exp(w)$.
  934. The Lambert W function has two partially real branches: the
  935. principal branch ($k = 0$) is real for real $z > -1/e$, and the
  936. $k = -1$ branch is real for $-1/e < z < 0$. All branches except
  937. $k = 0$ have a logarithmic singularity at $z = 0$.
  938. Examples
  939. ========
  940. >>> from sympy import LambertW
  941. >>> LambertW(1.2)
  942. 0.635564016364870
  943. >>> LambertW(1.2, -1).n()
  944. -1.34747534407696 - 4.41624341514535*I
  945. >>> LambertW(-1).is_real
  946. False
  947. References
  948. ==========
  949. .. [1] https://en.wikipedia.org/wiki/Lambert_W_function
  950. """
  951. _singularities = (-Pow(S.Exp1, -1, evaluate=False), S.ComplexInfinity)
  952. @classmethod
  953. def eval(cls, x, k=None):
  954. if k == S.Zero:
  955. return cls(x)
  956. elif k is None:
  957. k = S.Zero
  958. if k.is_zero:
  959. if x.is_zero:
  960. return S.Zero
  961. if x is S.Exp1:
  962. return S.One
  963. if x == -1/S.Exp1:
  964. return S.NegativeOne
  965. if x == -log(2)/2:
  966. return -log(2)
  967. if x == 2*log(2):
  968. return log(2)
  969. if x == -S.Pi/2:
  970. return S.ImaginaryUnit*S.Pi/2
  971. if x == exp(1 + S.Exp1):
  972. return S.Exp1
  973. if x is S.Infinity:
  974. return S.Infinity
  975. if x.is_zero:
  976. return S.Zero
  977. if fuzzy_not(k.is_zero):
  978. if x.is_zero:
  979. return S.NegativeInfinity
  980. if k is S.NegativeOne:
  981. if x == -S.Pi/2:
  982. return -S.ImaginaryUnit*S.Pi/2
  983. elif x == -1/S.Exp1:
  984. return S.NegativeOne
  985. elif x == -2*exp(-2):
  986. return -Integer(2)
  987. def fdiff(self, argindex=1):
  988. """
  989. Return the first derivative of this function.
  990. """
  991. x = self.args[0]
  992. if len(self.args) == 1:
  993. if argindex == 1:
  994. return LambertW(x)/(x*(1 + LambertW(x)))
  995. else:
  996. k = self.args[1]
  997. if argindex == 1:
  998. return LambertW(x, k)/(x*(1 + LambertW(x, k)))
  999. raise ArgumentIndexError(self, argindex)
  1000. def _eval_is_extended_real(self):
  1001. x = self.args[0]
  1002. if len(self.args) == 1:
  1003. k = S.Zero
  1004. else:
  1005. k = self.args[1]
  1006. if k.is_zero:
  1007. if (x + 1/S.Exp1).is_positive:
  1008. return True
  1009. elif (x + 1/S.Exp1).is_nonpositive:
  1010. return False
  1011. elif (k + 1).is_zero:
  1012. if x.is_negative and (x + 1/S.Exp1).is_positive:
  1013. return True
  1014. elif x.is_nonpositive or (x + 1/S.Exp1).is_nonnegative:
  1015. return False
  1016. elif fuzzy_not(k.is_zero) and fuzzy_not((k + 1).is_zero):
  1017. if x.is_extended_real:
  1018. return False
  1019. def _eval_is_finite(self):
  1020. return self.args[0].is_finite
  1021. def _eval_is_algebraic(self):
  1022. s = self.func(*self.args)
  1023. if s.func == self.func:
  1024. if fuzzy_not(self.args[0].is_zero) and self.args[0].is_algebraic:
  1025. return False
  1026. else:
  1027. return s.is_algebraic
  1028. def _eval_as_leading_term(self, x, logx=None, cdir=0):
  1029. if len(self.args) == 1:
  1030. arg = self.args[0]
  1031. arg0 = arg.subs(x, 0).cancel()
  1032. if not arg0.is_zero:
  1033. return self.func(arg0)
  1034. return arg.as_leading_term(x)
  1035. def _eval_nseries(self, x, n, logx, cdir=0):
  1036. if len(self.args) == 1:
  1037. from sympy.functions.elementary.integers import ceiling
  1038. from sympy.series.order import Order
  1039. arg = self.args[0].nseries(x, n=n, logx=logx)
  1040. lt = arg.compute_leading_term(x, logx=logx)
  1041. lte = 1
  1042. if lt.is_Pow:
  1043. lte = lt.exp
  1044. if ceiling(n/lte) >= 1:
  1045. s = Add(*[(-S.One)**(k - 1)*Integer(k)**(k - 2)/
  1046. factorial(k - 1)*arg**k for k in range(1, ceiling(n/lte))])
  1047. s = expand_multinomial(s)
  1048. else:
  1049. s = S.Zero
  1050. return s + Order(x**n, x)
  1051. return super()._eval_nseries(x, n, logx)
  1052. def _eval_is_zero(self):
  1053. x = self.args[0]
  1054. if len(self.args) == 1:
  1055. return x.is_zero
  1056. else:
  1057. return fuzzy_and([x.is_zero, self.args[1].is_zero])