integrals.py 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633
  1. from typing import Tuple as tTuple
  2. from sympy.concrete.expr_with_limits import AddWithLimits
  3. from sympy.core.add import Add
  4. from sympy.core.basic import Basic
  5. from sympy.core.containers import Tuple
  6. from sympy.core.expr import Expr
  7. from sympy.core.exprtools import factor_terms
  8. from sympy.core.function import diff
  9. from sympy.core.logic import fuzzy_bool
  10. from sympy.core.mul import Mul
  11. from sympy.core.numbers import oo, pi
  12. from sympy.core.relational import Ne
  13. from sympy.core.singleton import S
  14. from sympy.core.symbol import (Dummy, Symbol, Wild)
  15. from sympy.core.sympify import sympify
  16. from sympy.functions import Piecewise, sqrt, piecewise_fold, tan, cot, atan
  17. from sympy.functions.elementary.exponential import log
  18. from sympy.functions.elementary.integers import floor
  19. from sympy.functions.elementary.complexes import Abs, sign
  20. from sympy.functions.elementary.miscellaneous import Min, Max
  21. from .rationaltools import ratint
  22. from sympy.matrices import MatrixBase
  23. from sympy.polys import Poly, PolynomialError
  24. from sympy.series.formal import FormalPowerSeries
  25. from sympy.series.limits import limit
  26. from sympy.series.order import Order
  27. from sympy.tensor.functions import shape
  28. from sympy.utilities.exceptions import sympy_deprecation_warning
  29. from sympy.utilities.iterables import is_sequence
  30. from sympy.utilities.misc import filldedent
  31. class Integral(AddWithLimits):
  32. """Represents unevaluated integral."""
  33. __slots__ = ()
  34. args: tTuple[Expr, Tuple]
  35. def __new__(cls, function, *symbols, **assumptions):
  36. """Create an unevaluated integral.
  37. Explanation
  38. ===========
  39. Arguments are an integrand followed by one or more limits.
  40. If no limits are given and there is only one free symbol in the
  41. expression, that symbol will be used, otherwise an error will be
  42. raised.
  43. >>> from sympy import Integral
  44. >>> from sympy.abc import x, y
  45. >>> Integral(x)
  46. Integral(x, x)
  47. >>> Integral(y)
  48. Integral(y, y)
  49. When limits are provided, they are interpreted as follows (using
  50. ``x`` as though it were the variable of integration):
  51. (x,) or x - indefinite integral
  52. (x, a) - "evaluate at" integral is an abstract antiderivative
  53. (x, a, b) - definite integral
  54. The ``as_dummy`` method can be used to see which symbols cannot be
  55. targeted by subs: those with a prepended underscore cannot be
  56. changed with ``subs``. (Also, the integration variables themselves --
  57. the first element of a limit -- can never be changed by subs.)
  58. >>> i = Integral(x, x)
  59. >>> at = Integral(x, (x, x))
  60. >>> i.as_dummy()
  61. Integral(x, x)
  62. >>> at.as_dummy()
  63. Integral(_0, (_0, x))
  64. """
  65. #This will help other classes define their own definitions
  66. #of behaviour with Integral.
  67. if hasattr(function, '_eval_Integral'):
  68. return function._eval_Integral(*symbols, **assumptions)
  69. if isinstance(function, Poly):
  70. sympy_deprecation_warning(
  71. """
  72. integrate(Poly) and Integral(Poly) are deprecated. Instead,
  73. use the Poly.integrate() method, or convert the Poly to an
  74. Expr first with the Poly.as_expr() method.
  75. """,
  76. deprecated_since_version="1.6",
  77. active_deprecations_target="deprecated-integrate-poly")
  78. obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
  79. return obj
  80. def __getnewargs__(self):
  81. return (self.function,) + tuple([tuple(xab) for xab in self.limits])
  82. @property
  83. def free_symbols(self):
  84. """
  85. This method returns the symbols that will exist when the
  86. integral is evaluated. This is useful if one is trying to
  87. determine whether an integral depends on a certain
  88. symbol or not.
  89. Examples
  90. ========
  91. >>> from sympy import Integral
  92. >>> from sympy.abc import x, y
  93. >>> Integral(x, (x, y, 1)).free_symbols
  94. {y}
  95. See Also
  96. ========
  97. sympy.concrete.expr_with_limits.ExprWithLimits.function
  98. sympy.concrete.expr_with_limits.ExprWithLimits.limits
  99. sympy.concrete.expr_with_limits.ExprWithLimits.variables
  100. """
  101. return super().free_symbols
  102. def _eval_is_zero(self):
  103. # This is a very naive and quick test, not intended to do the integral to
  104. # answer whether it is zero or not, e.g. Integral(sin(x), (x, 0, 2*pi))
  105. # is zero but this routine should return None for that case. But, like
  106. # Mul, there are trivial situations for which the integral will be
  107. # zero so we check for those.
  108. if self.function.is_zero:
  109. return True
  110. got_none = False
  111. for l in self.limits:
  112. if len(l) == 3:
  113. z = (l[1] == l[2]) or (l[1] - l[2]).is_zero
  114. if z:
  115. return True
  116. elif z is None:
  117. got_none = True
  118. free = self.function.free_symbols
  119. for xab in self.limits:
  120. if len(xab) == 1:
  121. free.add(xab[0])
  122. continue
  123. if len(xab) == 2 and xab[0] not in free:
  124. if xab[1].is_zero:
  125. return True
  126. elif xab[1].is_zero is None:
  127. got_none = True
  128. # take integration symbol out of free since it will be replaced
  129. # with the free symbols in the limits
  130. free.discard(xab[0])
  131. # add in the new symbols
  132. for i in xab[1:]:
  133. free.update(i.free_symbols)
  134. if self.function.is_zero is False and got_none is False:
  135. return False
  136. def transform(self, x, u):
  137. r"""
  138. Performs a change of variables from `x` to `u` using the relationship
  139. given by `x` and `u` which will define the transformations `f` and `F`
  140. (which are inverses of each other) as follows:
  141. 1) If `x` is a Symbol (which is a variable of integration) then `u`
  142. will be interpreted as some function, f(u), with inverse F(u).
  143. This, in effect, just makes the substitution of x with f(x).
  144. 2) If `u` is a Symbol then `x` will be interpreted as some function,
  145. F(x), with inverse f(u). This is commonly referred to as
  146. u-substitution.
  147. Once f and F have been identified, the transformation is made as
  148. follows:
  149. .. math:: \int_a^b x \mathrm{d}x \rightarrow \int_{F(a)}^{F(b)} f(x)
  150. \frac{\mathrm{d}}{\mathrm{d}x}
  151. where `F(x)` is the inverse of `f(x)` and the limits and integrand have
  152. been corrected so as to retain the same value after integration.
  153. Notes
  154. =====
  155. The mappings, F(x) or f(u), must lead to a unique integral. Linear
  156. or rational linear expression, ``2*x``, ``1/x`` and ``sqrt(x)``, will
  157. always work; quadratic expressions like ``x**2 - 1`` are acceptable
  158. as long as the resulting integrand does not depend on the sign of
  159. the solutions (see examples).
  160. The integral will be returned unchanged if ``x`` is not a variable of
  161. integration.
  162. ``x`` must be (or contain) only one of of the integration variables. If
  163. ``u`` has more than one free symbol then it should be sent as a tuple
  164. (``u``, ``uvar``) where ``uvar`` identifies which variable is replacing
  165. the integration variable.
  166. XXX can it contain another integration variable?
  167. Examples
  168. ========
  169. >>> from sympy.abc import a, x, u
  170. >>> from sympy import Integral, cos, sqrt
  171. >>> i = Integral(x*cos(x**2 - 1), (x, 0, 1))
  172. transform can change the variable of integration
  173. >>> i.transform(x, u)
  174. Integral(u*cos(u**2 - 1), (u, 0, 1))
  175. transform can perform u-substitution as long as a unique
  176. integrand is obtained:
  177. >>> i.transform(x**2 - 1, u)
  178. Integral(cos(u)/2, (u, -1, 0))
  179. This attempt fails because x = +/-sqrt(u + 1) and the
  180. sign does not cancel out of the integrand:
  181. >>> Integral(cos(x**2 - 1), (x, 0, 1)).transform(x**2 - 1, u)
  182. Traceback (most recent call last):
  183. ...
  184. ValueError:
  185. The mapping between F(x) and f(u) did not give a unique integrand.
  186. transform can do a substitution. Here, the previous
  187. result is transformed back into the original expression
  188. using "u-substitution":
  189. >>> ui = _
  190. >>> _.transform(sqrt(u + 1), x) == i
  191. True
  192. We can accomplish the same with a regular substitution:
  193. >>> ui.transform(u, x**2 - 1) == i
  194. True
  195. If the `x` does not contain a symbol of integration then
  196. the integral will be returned unchanged. Integral `i` does
  197. not have an integration variable `a` so no change is made:
  198. >>> i.transform(a, x) == i
  199. True
  200. When `u` has more than one free symbol the symbol that is
  201. replacing `x` must be identified by passing `u` as a tuple:
  202. >>> Integral(x, (x, 0, 1)).transform(x, (u + a, u))
  203. Integral(a + u, (u, -a, 1 - a))
  204. >>> Integral(x, (x, 0, 1)).transform(x, (u + a, a))
  205. Integral(a + u, (a, -u, 1 - u))
  206. See Also
  207. ========
  208. sympy.concrete.expr_with_limits.ExprWithLimits.variables : Lists the integration variables
  209. as_dummy : Replace integration variables with dummy ones
  210. """
  211. d = Dummy('d')
  212. xfree = x.free_symbols.intersection(self.variables)
  213. if len(xfree) > 1:
  214. raise ValueError(
  215. 'F(x) can only contain one of: %s' % self.variables)
  216. xvar = xfree.pop() if xfree else d
  217. if xvar not in self.variables:
  218. return self
  219. u = sympify(u)
  220. if isinstance(u, Expr):
  221. ufree = u.free_symbols
  222. if len(ufree) == 0:
  223. raise ValueError(filldedent('''
  224. f(u) cannot be a constant'''))
  225. if len(ufree) > 1:
  226. raise ValueError(filldedent('''
  227. When f(u) has more than one free symbol, the one replacing x
  228. must be identified: pass f(u) as (f(u), u)'''))
  229. uvar = ufree.pop()
  230. else:
  231. u, uvar = u
  232. if uvar not in u.free_symbols:
  233. raise ValueError(filldedent('''
  234. Expecting a tuple (expr, symbol) where symbol identified
  235. a free symbol in expr, but symbol is not in expr's free
  236. symbols.'''))
  237. if not isinstance(uvar, Symbol):
  238. # This probably never evaluates to True
  239. raise ValueError(filldedent('''
  240. Expecting a tuple (expr, symbol) but didn't get
  241. a symbol; got %s''' % uvar))
  242. if x.is_Symbol and u.is_Symbol:
  243. return self.xreplace({x: u})
  244. if not x.is_Symbol and not u.is_Symbol:
  245. raise ValueError('either x or u must be a symbol')
  246. if uvar == xvar:
  247. return self.transform(x, (u.subs(uvar, d), d)).xreplace({d: uvar})
  248. if uvar in self.limits:
  249. raise ValueError(filldedent('''
  250. u must contain the same variable as in x
  251. or a variable that is not already an integration variable'''))
  252. from sympy.solvers.solvers import solve
  253. if not x.is_Symbol:
  254. F = [x.subs(xvar, d)]
  255. soln = solve(u - x, xvar, check=False)
  256. if not soln:
  257. raise ValueError('no solution for solve(F(x) - f(u), x)')
  258. f = [fi.subs(uvar, d) for fi in soln]
  259. else:
  260. f = [u.subs(uvar, d)]
  261. from sympy.simplify.simplify import posify
  262. pdiff, reps = posify(u - x)
  263. puvar = uvar.subs([(v, k) for k, v in reps.items()])
  264. soln = [s.subs(reps) for s in solve(pdiff, puvar)]
  265. if not soln:
  266. raise ValueError('no solution for solve(F(x) - f(u), u)')
  267. F = [fi.subs(xvar, d) for fi in soln]
  268. newfuncs = {(self.function.subs(xvar, fi)*fi.diff(d)
  269. ).subs(d, uvar) for fi in f}
  270. if len(newfuncs) > 1:
  271. raise ValueError(filldedent('''
  272. The mapping between F(x) and f(u) did not give
  273. a unique integrand.'''))
  274. newfunc = newfuncs.pop()
  275. def _calc_limit_1(F, a, b):
  276. """
  277. replace d with a, using subs if possible, otherwise limit
  278. where sign of b is considered
  279. """
  280. wok = F.subs(d, a)
  281. if wok is S.NaN or wok.is_finite is False and a.is_finite:
  282. return limit(sign(b)*F, d, a)
  283. return wok
  284. def _calc_limit(a, b):
  285. """
  286. replace d with a, using subs if possible, otherwise limit
  287. where sign of b is considered
  288. """
  289. avals = list({_calc_limit_1(Fi, a, b) for Fi in F})
  290. if len(avals) > 1:
  291. raise ValueError(filldedent('''
  292. The mapping between F(x) and f(u) did not
  293. give a unique limit.'''))
  294. return avals[0]
  295. newlimits = []
  296. for xab in self.limits:
  297. sym = xab[0]
  298. if sym == xvar:
  299. if len(xab) == 3:
  300. a, b = xab[1:]
  301. a, b = _calc_limit(a, b), _calc_limit(b, a)
  302. if fuzzy_bool(a - b > 0):
  303. a, b = b, a
  304. newfunc = -newfunc
  305. newlimits.append((uvar, a, b))
  306. elif len(xab) == 2:
  307. a = _calc_limit(xab[1], 1)
  308. newlimits.append((uvar, a))
  309. else:
  310. newlimits.append(uvar)
  311. else:
  312. newlimits.append(xab)
  313. return self.func(newfunc, *newlimits)
  314. def doit(self, **hints):
  315. """
  316. Perform the integration using any hints given.
  317. Examples
  318. ========
  319. >>> from sympy import Piecewise, S
  320. >>> from sympy.abc import x, t
  321. >>> p = x**2 + Piecewise((0, x/t < 0), (1, True))
  322. >>> p.integrate((t, S(4)/5, 1), (x, -1, 1))
  323. 1/3
  324. See Also
  325. ========
  326. sympy.integrals.trigonometry.trigintegrate
  327. sympy.integrals.heurisch.heurisch
  328. sympy.integrals.rationaltools.ratint
  329. as_sum : Approximate the integral using a sum
  330. """
  331. if not hints.get('integrals', True):
  332. return self
  333. deep = hints.get('deep', True)
  334. meijerg = hints.get('meijerg', None)
  335. conds = hints.get('conds', 'piecewise')
  336. risch = hints.get('risch', None)
  337. heurisch = hints.get('heurisch', None)
  338. manual = hints.get('manual', None)
  339. if len(list(filter(None, (manual, meijerg, risch, heurisch)))) > 1:
  340. raise ValueError("At most one of manual, meijerg, risch, heurisch can be True")
  341. elif manual:
  342. meijerg = risch = heurisch = False
  343. elif meijerg:
  344. manual = risch = heurisch = False
  345. elif risch:
  346. manual = meijerg = heurisch = False
  347. elif heurisch:
  348. manual = meijerg = risch = False
  349. eval_kwargs = {"meijerg": meijerg, "risch": risch, "manual": manual, "heurisch": heurisch,
  350. "conds": conds}
  351. if conds not in ('separate', 'piecewise', 'none'):
  352. raise ValueError('conds must be one of "separate", "piecewise", '
  353. '"none", got: %s' % conds)
  354. if risch and any(len(xab) > 1 for xab in self.limits):
  355. raise ValueError('risch=True is only allowed for indefinite integrals.')
  356. # check for the trivial zero
  357. if self.is_zero:
  358. return S.Zero
  359. # hacks to handle integrals of
  360. # nested summations
  361. from sympy.concrete.summations import Sum
  362. if isinstance(self.function, Sum):
  363. if any(v in self.function.limits[0] for v in self.variables):
  364. raise ValueError('Limit of the sum cannot be an integration variable.')
  365. if any(l.is_infinite for l in self.function.limits[0][1:]):
  366. return self
  367. _i = self
  368. _sum = self.function
  369. return _sum.func(_i.func(_sum.function, *_i.limits).doit(), *_sum.limits).doit()
  370. # now compute and check the function
  371. function = self.function
  372. if deep:
  373. function = function.doit(**hints)
  374. if function.is_zero:
  375. return S.Zero
  376. # hacks to handle special cases
  377. if isinstance(function, MatrixBase):
  378. return function.applyfunc(
  379. lambda f: self.func(f, *self.limits).doit(**hints))
  380. if isinstance(function, FormalPowerSeries):
  381. if len(self.limits) > 1:
  382. raise NotImplementedError
  383. xab = self.limits[0]
  384. if len(xab) > 1:
  385. return function.integrate(xab, **eval_kwargs)
  386. else:
  387. return function.integrate(xab[0], **eval_kwargs)
  388. # There is no trivial answer and special handling
  389. # is done so continue
  390. # first make sure any definite limits have integration
  391. # variables with matching assumptions
  392. reps = {}
  393. for xab in self.limits:
  394. if len(xab) != 3:
  395. # it makes sense to just make
  396. # all x real but in practice with the
  397. # current state of integration...this
  398. # doesn't work out well
  399. # x = xab[0]
  400. # if x not in reps and not x.is_real:
  401. # reps[x] = Dummy(real=True)
  402. continue
  403. x, a, b = xab
  404. l = (a, b)
  405. if all(i.is_nonnegative for i in l) and not x.is_nonnegative:
  406. d = Dummy(positive=True)
  407. elif all(i.is_nonpositive for i in l) and not x.is_nonpositive:
  408. d = Dummy(negative=True)
  409. elif all(i.is_real for i in l) and not x.is_real:
  410. d = Dummy(real=True)
  411. else:
  412. d = None
  413. if d:
  414. reps[x] = d
  415. if reps:
  416. undo = {v: k for k, v in reps.items()}
  417. did = self.xreplace(reps).doit(**hints)
  418. if isinstance(did, tuple): # when separate=True
  419. did = tuple([i.xreplace(undo) for i in did])
  420. else:
  421. did = did.xreplace(undo)
  422. return did
  423. # continue with existing assumptions
  424. undone_limits = []
  425. # ulj = free symbols of any undone limits' upper and lower limits
  426. ulj = set()
  427. for xab in self.limits:
  428. # compute uli, the free symbols in the
  429. # Upper and Lower limits of limit I
  430. if len(xab) == 1:
  431. uli = set(xab[:1])
  432. elif len(xab) == 2:
  433. uli = xab[1].free_symbols
  434. elif len(xab) == 3:
  435. uli = xab[1].free_symbols.union(xab[2].free_symbols)
  436. # this integral can be done as long as there is no blocking
  437. # limit that has been undone. An undone limit is blocking if
  438. # it contains an integration variable that is in this limit's
  439. # upper or lower free symbols or vice versa
  440. if xab[0] in ulj or any(v[0] in uli for v in undone_limits):
  441. undone_limits.append(xab)
  442. ulj.update(uli)
  443. function = self.func(*([function] + [xab]))
  444. factored_function = function.factor()
  445. if not isinstance(factored_function, Integral):
  446. function = factored_function
  447. continue
  448. if function.has(Abs, sign) and (
  449. (len(xab) < 3 and all(x.is_extended_real for x in xab)) or
  450. (len(xab) == 3 and all(x.is_extended_real and not x.is_infinite for
  451. x in xab[1:]))):
  452. # some improper integrals are better off with Abs
  453. xr = Dummy("xr", real=True)
  454. function = (function.xreplace({xab[0]: xr})
  455. .rewrite(Piecewise).xreplace({xr: xab[0]}))
  456. elif function.has(Min, Max):
  457. function = function.rewrite(Piecewise)
  458. if (function.has(Piecewise) and
  459. not isinstance(function, Piecewise)):
  460. function = piecewise_fold(function)
  461. if isinstance(function, Piecewise):
  462. if len(xab) == 1:
  463. antideriv = function._eval_integral(xab[0],
  464. **eval_kwargs)
  465. else:
  466. antideriv = self._eval_integral(
  467. function, xab[0], **eval_kwargs)
  468. else:
  469. # There are a number of tradeoffs in using the
  470. # Meijer G method. It can sometimes be a lot faster
  471. # than other methods, and sometimes slower. And
  472. # there are certain types of integrals for which it
  473. # is more likely to work than others. These
  474. # heuristics are incorporated in deciding what
  475. # integration methods to try, in what order. See the
  476. # integrate() docstring for details.
  477. def try_meijerg(function, xab):
  478. ret = None
  479. if len(xab) == 3 and meijerg is not False:
  480. x, a, b = xab
  481. try:
  482. res = meijerint_definite(function, x, a, b)
  483. except NotImplementedError:
  484. _debug('NotImplementedError '
  485. 'from meijerint_definite')
  486. res = None
  487. if res is not None:
  488. f, cond = res
  489. if conds == 'piecewise':
  490. u = self.func(function, (x, a, b))
  491. # if Piecewise modifies cond too
  492. # much it may not be recognized by
  493. # _condsimp pattern matching so just
  494. # turn off all evaluation
  495. return Piecewise((f, cond), (u, True),
  496. evaluate=False)
  497. elif conds == 'separate':
  498. if len(self.limits) != 1:
  499. raise ValueError(filldedent('''
  500. conds=separate not supported in
  501. multiple integrals'''))
  502. ret = f, cond
  503. else:
  504. ret = f
  505. return ret
  506. meijerg1 = meijerg
  507. if (meijerg is not False and
  508. len(xab) == 3 and xab[1].is_extended_real and xab[2].is_extended_real
  509. and not function.is_Poly and
  510. (xab[1].has(oo, -oo) or xab[2].has(oo, -oo))):
  511. ret = try_meijerg(function, xab)
  512. if ret is not None:
  513. function = ret
  514. continue
  515. meijerg1 = False
  516. # If the special meijerg code did not succeed in
  517. # finding a definite integral, then the code using
  518. # meijerint_indefinite will not either (it might
  519. # find an antiderivative, but the answer is likely
  520. # to be nonsensical). Thus if we are requested to
  521. # only use Meijer G-function methods, we give up at
  522. # this stage. Otherwise we just disable G-function
  523. # methods.
  524. if meijerg1 is False and meijerg is True:
  525. antideriv = None
  526. else:
  527. antideriv = self._eval_integral(
  528. function, xab[0], **eval_kwargs)
  529. if antideriv is None and meijerg is True:
  530. ret = try_meijerg(function, xab)
  531. if ret is not None:
  532. function = ret
  533. continue
  534. final = hints.get('final', True)
  535. # dotit may be iterated but floor terms making atan and acot
  536. # continuous should only be added in the final round
  537. if (final and not isinstance(antideriv, Integral) and
  538. antideriv is not None):
  539. for atan_term in antideriv.atoms(atan):
  540. atan_arg = atan_term.args[0]
  541. # Checking `atan_arg` to be linear combination of `tan` or `cot`
  542. for tan_part in atan_arg.atoms(tan):
  543. x1 = Dummy('x1')
  544. tan_exp1 = atan_arg.subs(tan_part, x1)
  545. # The coefficient of `tan` should be constant
  546. coeff = tan_exp1.diff(x1)
  547. if x1 not in coeff.free_symbols:
  548. a = tan_part.args[0]
  549. antideriv = antideriv.subs(atan_term, Add(atan_term,
  550. sign(coeff)*pi*floor((a-pi/2)/pi)))
  551. for cot_part in atan_arg.atoms(cot):
  552. x1 = Dummy('x1')
  553. cot_exp1 = atan_arg.subs(cot_part, x1)
  554. # The coefficient of `cot` should be constant
  555. coeff = cot_exp1.diff(x1)
  556. if x1 not in coeff.free_symbols:
  557. a = cot_part.args[0]
  558. antideriv = antideriv.subs(atan_term, Add(atan_term,
  559. sign(coeff)*pi*floor((a)/pi)))
  560. if antideriv is None:
  561. undone_limits.append(xab)
  562. function = self.func(*([function] + [xab])).factor()
  563. factored_function = function.factor()
  564. if not isinstance(factored_function, Integral):
  565. function = factored_function
  566. continue
  567. else:
  568. if len(xab) == 1:
  569. function = antideriv
  570. else:
  571. if len(xab) == 3:
  572. x, a, b = xab
  573. elif len(xab) == 2:
  574. x, b = xab
  575. a = None
  576. else:
  577. raise NotImplementedError
  578. if deep:
  579. if isinstance(a, Basic):
  580. a = a.doit(**hints)
  581. if isinstance(b, Basic):
  582. b = b.doit(**hints)
  583. if antideriv.is_Poly:
  584. gens = list(antideriv.gens)
  585. gens.remove(x)
  586. antideriv = antideriv.as_expr()
  587. function = antideriv._eval_interval(x, a, b)
  588. function = Poly(function, *gens)
  589. else:
  590. def is_indef_int(g, x):
  591. return (isinstance(g, Integral) and
  592. any(i == (x,) for i in g.limits))
  593. def eval_factored(f, x, a, b):
  594. # _eval_interval for integrals with
  595. # (constant) factors
  596. # a single indefinite integral is assumed
  597. args = []
  598. for g in Mul.make_args(f):
  599. if is_indef_int(g, x):
  600. args.append(g._eval_interval(x, a, b))
  601. else:
  602. args.append(g)
  603. return Mul(*args)
  604. integrals, others, piecewises = [], [], []
  605. for f in Add.make_args(antideriv):
  606. if any(is_indef_int(g, x)
  607. for g in Mul.make_args(f)):
  608. integrals.append(f)
  609. elif any(isinstance(g, Piecewise)
  610. for g in Mul.make_args(f)):
  611. piecewises.append(piecewise_fold(f))
  612. else:
  613. others.append(f)
  614. uneval = Add(*[eval_factored(f, x, a, b)
  615. for f in integrals])
  616. try:
  617. evalued = Add(*others)._eval_interval(x, a, b)
  618. evalued_pw = piecewise_fold(Add(*piecewises))._eval_interval(x, a, b)
  619. function = uneval + evalued + evalued_pw
  620. except NotImplementedError:
  621. # This can happen if _eval_interval depends in a
  622. # complicated way on limits that cannot be computed
  623. undone_limits.append(xab)
  624. function = self.func(*([function] + [xab]))
  625. factored_function = function.factor()
  626. if not isinstance(factored_function, Integral):
  627. function = factored_function
  628. return function
  629. def _eval_derivative(self, sym):
  630. """Evaluate the derivative of the current Integral object by
  631. differentiating under the integral sign [1], using the Fundamental
  632. Theorem of Calculus [2] when possible.
  633. Explanation
  634. ===========
  635. Whenever an Integral is encountered that is equivalent to zero or
  636. has an integrand that is independent of the variable of integration
  637. those integrals are performed. All others are returned as Integral
  638. instances which can be resolved with doit() (provided they are integrable).
  639. References
  640. ==========
  641. .. [1] https://en.wikipedia.org/wiki/Differentiation_under_the_integral_sign
  642. .. [2] https://en.wikipedia.org/wiki/Fundamental_theorem_of_calculus
  643. Examples
  644. ========
  645. >>> from sympy import Integral
  646. >>> from sympy.abc import x, y
  647. >>> i = Integral(x + y, y, (y, 1, x))
  648. >>> i.diff(x)
  649. Integral(x + y, (y, x)) + Integral(1, y, (y, 1, x))
  650. >>> i.doit().diff(x) == i.diff(x).doit()
  651. True
  652. >>> i.diff(y)
  653. 0
  654. The previous must be true since there is no y in the evaluated integral:
  655. >>> i.free_symbols
  656. {x}
  657. >>> i.doit()
  658. 2*x**3/3 - x/2 - 1/6
  659. """
  660. # differentiate under the integral sign; we do not
  661. # check for regularity conditions (TODO), see issue 4215
  662. # get limits and the function
  663. f, limits = self.function, list(self.limits)
  664. # the order matters if variables of integration appear in the limits
  665. # so work our way in from the outside to the inside.
  666. limit = limits.pop(-1)
  667. if len(limit) == 3:
  668. x, a, b = limit
  669. elif len(limit) == 2:
  670. x, b = limit
  671. a = None
  672. else:
  673. a = b = None
  674. x = limit[0]
  675. if limits: # f is the argument to an integral
  676. f = self.func(f, *tuple(limits))
  677. # assemble the pieces
  678. def _do(f, ab):
  679. dab_dsym = diff(ab, sym)
  680. if not dab_dsym:
  681. return S.Zero
  682. if isinstance(f, Integral):
  683. limits = [(x, x) if (len(l) == 1 and l[0] == x) else l
  684. for l in f.limits]
  685. f = self.func(f.function, *limits)
  686. return f.subs(x, ab)*dab_dsym
  687. rv = S.Zero
  688. if b is not None:
  689. rv += _do(f, b)
  690. if a is not None:
  691. rv -= _do(f, a)
  692. if len(limit) == 1 and sym == x:
  693. # the dummy variable *is* also the real-world variable
  694. arg = f
  695. rv += arg
  696. else:
  697. # the dummy variable might match sym but it's
  698. # only a dummy and the actual variable is determined
  699. # by the limits, so mask off the variable of integration
  700. # while differentiating
  701. u = Dummy('u')
  702. arg = f.subs(x, u).diff(sym).subs(u, x)
  703. if arg:
  704. rv += self.func(arg, (x, a, b))
  705. return rv
  706. def _eval_integral(self, f, x, meijerg=None, risch=None, manual=None,
  707. heurisch=None, conds='piecewise',final=None):
  708. """
  709. Calculate the anti-derivative to the function f(x).
  710. Explanation
  711. ===========
  712. The following algorithms are applied (roughly in this order):
  713. 1. Simple heuristics (based on pattern matching and integral table):
  714. - most frequently used functions (e.g. polynomials, products of
  715. trig functions)
  716. 2. Integration of rational functions:
  717. - A complete algorithm for integrating rational functions is
  718. implemented (the Lazard-Rioboo-Trager algorithm). The algorithm
  719. also uses the partial fraction decomposition algorithm
  720. implemented in apart() as a preprocessor to make this process
  721. faster. Note that the integral of a rational function is always
  722. elementary, but in general, it may include a RootSum.
  723. 3. Full Risch algorithm:
  724. - The Risch algorithm is a complete decision
  725. procedure for integrating elementary functions, which means that
  726. given any elementary function, it will either compute an
  727. elementary antiderivative, or else prove that none exists.
  728. Currently, part of transcendental case is implemented, meaning
  729. elementary integrals containing exponentials, logarithms, and
  730. (soon!) trigonometric functions can be computed. The algebraic
  731. case, e.g., functions containing roots, is much more difficult
  732. and is not implemented yet.
  733. - If the routine fails (because the integrand is not elementary, or
  734. because a case is not implemented yet), it continues on to the
  735. next algorithms below. If the routine proves that the integrals
  736. is nonelementary, it still moves on to the algorithms below,
  737. because we might be able to find a closed-form solution in terms
  738. of special functions. If risch=True, however, it will stop here.
  739. 4. The Meijer G-Function algorithm:
  740. - This algorithm works by first rewriting the integrand in terms of
  741. very general Meijer G-Function (meijerg in SymPy), integrating
  742. it, and then rewriting the result back, if possible. This
  743. algorithm is particularly powerful for definite integrals (which
  744. is actually part of a different method of Integral), since it can
  745. compute closed-form solutions of definite integrals even when no
  746. closed-form indefinite integral exists. But it also is capable
  747. of computing many indefinite integrals as well.
  748. - Another advantage of this method is that it can use some results
  749. about the Meijer G-Function to give a result in terms of a
  750. Piecewise expression, which allows to express conditionally
  751. convergent integrals.
  752. - Setting meijerg=True will cause integrate() to use only this
  753. method.
  754. 5. The "manual integration" algorithm:
  755. - This algorithm tries to mimic how a person would find an
  756. antiderivative by hand, for example by looking for a
  757. substitution or applying integration by parts. This algorithm
  758. does not handle as many integrands but can return results in a
  759. more familiar form.
  760. - Sometimes this algorithm can evaluate parts of an integral; in
  761. this case integrate() will try to evaluate the rest of the
  762. integrand using the other methods here.
  763. - Setting manual=True will cause integrate() to use only this
  764. method.
  765. 6. The Heuristic Risch algorithm:
  766. - This is a heuristic version of the Risch algorithm, meaning that
  767. it is not deterministic. This is tried as a last resort because
  768. it can be very slow. It is still used because not enough of the
  769. full Risch algorithm is implemented, so that there are still some
  770. integrals that can only be computed using this method. The goal
  771. is to implement enough of the Risch and Meijer G-function methods
  772. so that this can be deleted.
  773. Setting heurisch=True will cause integrate() to use only this
  774. method. Set heurisch=False to not use it.
  775. """
  776. from sympy.integrals.risch import risch_integrate, NonElementaryIntegral
  777. from sympy.integrals.manualintegrate import manualintegrate
  778. if risch:
  779. try:
  780. return risch_integrate(f, x, conds=conds)
  781. except NotImplementedError:
  782. return None
  783. if manual:
  784. try:
  785. result = manualintegrate(f, x)
  786. if result is not None and result.func != Integral:
  787. return result
  788. except (ValueError, PolynomialError):
  789. pass
  790. eval_kwargs = {"meijerg": meijerg, "risch": risch, "manual": manual,
  791. "heurisch": heurisch, "conds": conds}
  792. # if it is a poly(x) then let the polynomial integrate itself (fast)
  793. #
  794. # It is important to make this check first, otherwise the other code
  795. # will return a SymPy expression instead of a Polynomial.
  796. #
  797. # see Polynomial for details.
  798. if isinstance(f, Poly) and not (manual or meijerg or risch):
  799. # Note: this is deprecated, but the deprecation warning is already
  800. # issued in the Integral constructor.
  801. return f.integrate(x)
  802. # Piecewise antiderivatives need to call special integrate.
  803. if isinstance(f, Piecewise):
  804. return f.piecewise_integrate(x, **eval_kwargs)
  805. # let's cut it short if `f` does not depend on `x`; if
  806. # x is only a dummy, that will be handled below
  807. if not f.has(x):
  808. return f*x
  809. # try to convert to poly(x) and then integrate if successful (fast)
  810. poly = f.as_poly(x)
  811. if poly is not None and not (manual or meijerg or risch):
  812. return poly.integrate().as_expr()
  813. if risch is not False:
  814. try:
  815. result, i = risch_integrate(f, x, separate_integral=True,
  816. conds=conds)
  817. except NotImplementedError:
  818. pass
  819. else:
  820. if i:
  821. # There was a nonelementary integral. Try integrating it.
  822. # if no part of the NonElementaryIntegral is integrated by
  823. # the Risch algorithm, then use the original function to
  824. # integrate, instead of re-written one
  825. if result == 0:
  826. return NonElementaryIntegral(f, x).doit(risch=False)
  827. else:
  828. return result + i.doit(risch=False)
  829. else:
  830. return result
  831. # since Integral(f=g1+g2+...) == Integral(g1) + Integral(g2) + ...
  832. # we are going to handle Add terms separately,
  833. # if `f` is not Add -- we only have one term
  834. # Note that in general, this is a bad idea, because Integral(g1) +
  835. # Integral(g2) might not be computable, even if Integral(g1 + g2) is.
  836. # For example, Integral(x**x + x**x*log(x)). But many heuristics only
  837. # work term-wise. So we compute this step last, after trying
  838. # risch_integrate. We also try risch_integrate again in this loop,
  839. # because maybe the integral is a sum of an elementary part and a
  840. # nonelementary part (like erf(x) + exp(x)). risch_integrate() is
  841. # quite fast, so this is acceptable.
  842. from sympy.simplify.fu import sincos_to_sum
  843. parts = []
  844. args = Add.make_args(f)
  845. for g in args:
  846. coeff, g = g.as_independent(x)
  847. # g(x) = const
  848. if g is S.One and not meijerg:
  849. parts.append(coeff*x)
  850. continue
  851. # g(x) = expr + O(x**n)
  852. order_term = g.getO()
  853. if order_term is not None:
  854. h = self._eval_integral(g.removeO(), x, **eval_kwargs)
  855. if h is not None:
  856. h_order_expr = self._eval_integral(order_term.expr, x, **eval_kwargs)
  857. if h_order_expr is not None:
  858. h_order_term = order_term.func(
  859. h_order_expr, *order_term.variables)
  860. parts.append(coeff*(h + h_order_term))
  861. continue
  862. # NOTE: if there is O(x**n) and we fail to integrate then
  863. # there is no point in trying other methods because they
  864. # will fail, too.
  865. return None
  866. # c
  867. # g(x) = (a*x+b)
  868. if g.is_Pow and not g.exp.has(x) and not meijerg:
  869. a = Wild('a', exclude=[x])
  870. b = Wild('b', exclude=[x])
  871. M = g.base.match(a*x + b)
  872. if M is not None:
  873. if g.exp == -1:
  874. h = log(g.base)
  875. elif conds != 'piecewise':
  876. h = g.base**(g.exp + 1) / (g.exp + 1)
  877. else:
  878. h1 = log(g.base)
  879. h2 = g.base**(g.exp + 1) / (g.exp + 1)
  880. h = Piecewise((h2, Ne(g.exp, -1)), (h1, True))
  881. parts.append(coeff * h / M[a])
  882. continue
  883. # poly(x)
  884. # g(x) = -------
  885. # poly(x)
  886. if g.is_rational_function(x) and not (manual or meijerg or risch):
  887. parts.append(coeff * ratint(g, x))
  888. continue
  889. if not (manual or meijerg or risch):
  890. # g(x) = Mul(trig)
  891. h = trigintegrate(g, x, conds=conds)
  892. if h is not None:
  893. parts.append(coeff * h)
  894. continue
  895. # g(x) has at least a DiracDelta term
  896. h = deltaintegrate(g, x)
  897. if h is not None:
  898. parts.append(coeff * h)
  899. continue
  900. from .singularityfunctions import singularityintegrate
  901. # g(x) has at least a Singularity Function term
  902. h = singularityintegrate(g, x)
  903. if h is not None:
  904. parts.append(coeff * h)
  905. continue
  906. # Try risch again.
  907. if risch is not False:
  908. try:
  909. h, i = risch_integrate(g, x,
  910. separate_integral=True, conds=conds)
  911. except NotImplementedError:
  912. h = None
  913. else:
  914. if i:
  915. h = h + i.doit(risch=False)
  916. parts.append(coeff*h)
  917. continue
  918. # fall back to heurisch
  919. if heurisch is not False:
  920. from sympy.integrals.heurisch import (heurisch as heurisch_,
  921. heurisch_wrapper)
  922. try:
  923. if conds == 'piecewise':
  924. h = heurisch_wrapper(g, x, hints=[])
  925. else:
  926. h = heurisch_(g, x, hints=[])
  927. except PolynomialError:
  928. # XXX: this exception means there is a bug in the
  929. # implementation of heuristic Risch integration
  930. # algorithm.
  931. h = None
  932. else:
  933. h = None
  934. if meijerg is not False and h is None:
  935. # rewrite using G functions
  936. try:
  937. h = meijerint_indefinite(g, x)
  938. except NotImplementedError:
  939. _debug('NotImplementedError from meijerint_definite')
  940. if h is not None:
  941. parts.append(coeff * h)
  942. continue
  943. if h is None and manual is not False:
  944. try:
  945. result = manualintegrate(g, x)
  946. if result is not None and not isinstance(result, Integral):
  947. if result.has(Integral) and not manual:
  948. # Try to have other algorithms do the integrals
  949. # manualintegrate can't handle,
  950. # unless we were asked to use manual only.
  951. # Keep the rest of eval_kwargs in case another
  952. # method was set to False already
  953. new_eval_kwargs = eval_kwargs
  954. new_eval_kwargs["manual"] = False
  955. new_eval_kwargs["final"] = False
  956. result = result.func(*[
  957. arg.doit(**new_eval_kwargs) if
  958. arg.has(Integral) else arg
  959. for arg in result.args
  960. ]).expand(multinomial=False,
  961. log=False,
  962. power_exp=False,
  963. power_base=False)
  964. if not result.has(Integral):
  965. parts.append(coeff * result)
  966. continue
  967. except (ValueError, PolynomialError):
  968. # can't handle some SymPy expressions
  969. pass
  970. # if we failed maybe it was because we had
  971. # a product that could have been expanded,
  972. # so let's try an expansion of the whole
  973. # thing before giving up; we don't try this
  974. # at the outset because there are things
  975. # that cannot be solved unless they are
  976. # NOT expanded e.g., x**x*(1+log(x)). There
  977. # should probably be a checker somewhere in this
  978. # routine to look for such cases and try to do
  979. # collection on the expressions if they are already
  980. # in an expanded form
  981. if not h and len(args) == 1:
  982. f = sincos_to_sum(f).expand(mul=True, deep=False)
  983. if f.is_Add:
  984. # Note: risch will be identical on the expanded
  985. # expression, but maybe it will be able to pick out parts,
  986. # like x*(exp(x) + erf(x)).
  987. return self._eval_integral(f, x, **eval_kwargs)
  988. if h is not None:
  989. parts.append(coeff * h)
  990. else:
  991. return None
  992. return Add(*parts)
  993. def _eval_lseries(self, x, logx=None, cdir=0):
  994. expr = self.as_dummy()
  995. symb = x
  996. for l in expr.limits:
  997. if x in l[1:]:
  998. symb = l[0]
  999. break
  1000. for term in expr.function.lseries(symb, logx):
  1001. yield integrate(term, *expr.limits)
  1002. def _eval_nseries(self, x, n, logx=None, cdir=0):
  1003. expr = self.as_dummy()
  1004. symb = x
  1005. for l in expr.limits:
  1006. if x in l[1:]:
  1007. symb = l[0]
  1008. break
  1009. terms, order = expr.function.nseries(
  1010. x=symb, n=n, logx=logx).as_coeff_add(Order)
  1011. order = [o.subs(symb, x) for o in order]
  1012. return integrate(terms, *expr.limits) + Add(*order)*x
  1013. def _eval_as_leading_term(self, x, logx=None, cdir=0):
  1014. series_gen = self.args[0].lseries(x)
  1015. for leading_term in series_gen:
  1016. if leading_term != 0:
  1017. break
  1018. return integrate(leading_term, *self.args[1:])
  1019. def _eval_simplify(self, **kwargs):
  1020. expr = factor_terms(self)
  1021. if isinstance(expr, Integral):
  1022. from sympy.simplify.simplify import simplify
  1023. return expr.func(*[simplify(i, **kwargs) for i in expr.args])
  1024. return expr.simplify(**kwargs)
  1025. def as_sum(self, n=None, method="midpoint", evaluate=True):
  1026. """
  1027. Approximates a definite integral by a sum.
  1028. Parameters
  1029. ==========
  1030. n :
  1031. The number of subintervals to use, optional.
  1032. method :
  1033. One of: 'left', 'right', 'midpoint', 'trapezoid'.
  1034. evaluate : bool
  1035. If False, returns an unevaluated Sum expression. The default
  1036. is True, evaluate the sum.
  1037. Notes
  1038. =====
  1039. These methods of approximate integration are described in [1].
  1040. Examples
  1041. ========
  1042. >>> from sympy import Integral, sin, sqrt
  1043. >>> from sympy.abc import x, n
  1044. >>> e = Integral(sin(x), (x, 3, 7))
  1045. >>> e
  1046. Integral(sin(x), (x, 3, 7))
  1047. For demonstration purposes, this interval will only be split into 2
  1048. regions, bounded by [3, 5] and [5, 7].
  1049. The left-hand rule uses function evaluations at the left of each
  1050. interval:
  1051. >>> e.as_sum(2, 'left')
  1052. 2*sin(5) + 2*sin(3)
  1053. The midpoint rule uses evaluations at the center of each interval:
  1054. >>> e.as_sum(2, 'midpoint')
  1055. 2*sin(4) + 2*sin(6)
  1056. The right-hand rule uses function evaluations at the right of each
  1057. interval:
  1058. >>> e.as_sum(2, 'right')
  1059. 2*sin(5) + 2*sin(7)
  1060. The trapezoid rule uses function evaluations on both sides of the
  1061. intervals. This is equivalent to taking the average of the left and
  1062. right hand rule results:
  1063. >>> e.as_sum(2, 'trapezoid')
  1064. 2*sin(5) + sin(3) + sin(7)
  1065. >>> (e.as_sum(2, 'left') + e.as_sum(2, 'right'))/2 == _
  1066. True
  1067. Here, the discontinuity at x = 0 can be avoided by using the
  1068. midpoint or right-hand method:
  1069. >>> e = Integral(1/sqrt(x), (x, 0, 1))
  1070. >>> e.as_sum(5).n(4)
  1071. 1.730
  1072. >>> e.as_sum(10).n(4)
  1073. 1.809
  1074. >>> e.doit().n(4) # the actual value is 2
  1075. 2.000
  1076. The left- or trapezoid method will encounter the discontinuity and
  1077. return infinity:
  1078. >>> e.as_sum(5, 'left')
  1079. zoo
  1080. The number of intervals can be symbolic. If omitted, a dummy symbol
  1081. will be used for it.
  1082. >>> e = Integral(x**2, (x, 0, 2))
  1083. >>> e.as_sum(n, 'right').expand()
  1084. 8/3 + 4/n + 4/(3*n**2)
  1085. This shows that the midpoint rule is more accurate, as its error
  1086. term decays as the square of n:
  1087. >>> e.as_sum(method='midpoint').expand()
  1088. 8/3 - 2/(3*_n**2)
  1089. A symbolic sum is returned with evaluate=False:
  1090. >>> e.as_sum(n, 'midpoint', evaluate=False)
  1091. 2*Sum((2*_k/n - 1/n)**2, (_k, 1, n))/n
  1092. See Also
  1093. ========
  1094. Integral.doit : Perform the integration using any hints
  1095. References
  1096. ==========
  1097. .. [1] https://en.wikipedia.org/wiki/Riemann_sum#Riemann_summation_methods
  1098. """
  1099. from sympy.concrete.summations import Sum
  1100. limits = self.limits
  1101. if len(limits) > 1:
  1102. raise NotImplementedError(
  1103. "Multidimensional midpoint rule not implemented yet")
  1104. else:
  1105. limit = limits[0]
  1106. if (len(limit) != 3 or limit[1].is_finite is False or
  1107. limit[2].is_finite is False):
  1108. raise ValueError("Expecting a definite integral over "
  1109. "a finite interval.")
  1110. if n is None:
  1111. n = Dummy('n', integer=True, positive=True)
  1112. else:
  1113. n = sympify(n)
  1114. if (n.is_positive is False or n.is_integer is False or
  1115. n.is_finite is False):
  1116. raise ValueError("n must be a positive integer, got %s" % n)
  1117. x, a, b = limit
  1118. dx = (b - a)/n
  1119. k = Dummy('k', integer=True, positive=True)
  1120. f = self.function
  1121. if method == "left":
  1122. result = dx*Sum(f.subs(x, a + (k-1)*dx), (k, 1, n))
  1123. elif method == "right":
  1124. result = dx*Sum(f.subs(x, a + k*dx), (k, 1, n))
  1125. elif method == "midpoint":
  1126. result = dx*Sum(f.subs(x, a + k*dx - dx/2), (k, 1, n))
  1127. elif method == "trapezoid":
  1128. result = dx*((f.subs(x, a) + f.subs(x, b))/2 +
  1129. Sum(f.subs(x, a + k*dx), (k, 1, n - 1)))
  1130. else:
  1131. raise ValueError("Unknown method %s" % method)
  1132. return result.doit() if evaluate else result
  1133. def principal_value(self, **kwargs):
  1134. """
  1135. Compute the Cauchy Principal Value of the definite integral of a real function in the given interval
  1136. on the real axis.
  1137. Explanation
  1138. ===========
  1139. In mathematics, the Cauchy principal value, is a method for assigning values to certain improper
  1140. integrals which would otherwise be undefined.
  1141. Examples
  1142. ========
  1143. >>> from sympy import Integral, oo
  1144. >>> from sympy.abc import x
  1145. >>> Integral(x+1, (x, -oo, oo)).principal_value()
  1146. oo
  1147. >>> f = 1 / (x**3)
  1148. >>> Integral(f, (x, -oo, oo)).principal_value()
  1149. 0
  1150. >>> Integral(f, (x, -10, 10)).principal_value()
  1151. 0
  1152. >>> Integral(f, (x, -10, oo)).principal_value() + Integral(f, (x, -oo, 10)).principal_value()
  1153. 0
  1154. References
  1155. ==========
  1156. .. [1] https://en.wikipedia.org/wiki/Cauchy_principal_value
  1157. .. [2] https://mathworld.wolfram.com/CauchyPrincipalValue.html
  1158. """
  1159. if len(self.limits) != 1 or len(list(self.limits[0])) != 3:
  1160. raise ValueError("You need to insert a variable, lower_limit, and upper_limit correctly to calculate "
  1161. "cauchy's principal value")
  1162. x, a, b = self.limits[0]
  1163. if not (a.is_comparable and b.is_comparable and a <= b):
  1164. raise ValueError("The lower_limit must be smaller than or equal to the upper_limit to calculate "
  1165. "cauchy's principal value. Also, a and b need to be comparable.")
  1166. if a == b:
  1167. return S.Zero
  1168. from sympy.calculus.singularities import singularities
  1169. r = Dummy('r')
  1170. f = self.function
  1171. singularities_list = [s for s in singularities(f, x) if s.is_comparable and a <= s <= b]
  1172. for i in singularities_list:
  1173. if i in (a, b):
  1174. raise ValueError(
  1175. 'The principal value is not defined in the given interval due to singularity at %d.' % (i))
  1176. F = integrate(f, x, **kwargs)
  1177. if F.has(Integral):
  1178. return self
  1179. if a is -oo and b is oo:
  1180. I = limit(F - F.subs(x, -x), x, oo)
  1181. else:
  1182. I = limit(F, x, b, '-') - limit(F, x, a, '+')
  1183. for s in singularities_list:
  1184. I += limit(((F.subs(x, s - r)) - F.subs(x, s + r)), r, 0, '+')
  1185. return I
  1186. def integrate(*args, meijerg=None, conds='piecewise', risch=None, heurisch=None, manual=None, **kwargs):
  1187. """integrate(f, var, ...)
  1188. .. deprecated:: 1.6
  1189. Using ``integrate()`` with :class:`~.Poly` is deprecated. Use
  1190. :meth:`.Poly.integrate` instead. See :ref:`deprecated-integrate-poly`.
  1191. Explanation
  1192. ===========
  1193. Compute definite or indefinite integral of one or more variables
  1194. using Risch-Norman algorithm and table lookup. This procedure is
  1195. able to handle elementary algebraic and transcendental functions
  1196. and also a huge class of special functions, including Airy,
  1197. Bessel, Whittaker and Lambert.
  1198. var can be:
  1199. - a symbol -- indefinite integration
  1200. - a tuple (symbol, a) -- indefinite integration with result
  1201. given with ``a`` replacing ``symbol``
  1202. - a tuple (symbol, a, b) -- definite integration
  1203. Several variables can be specified, in which case the result is
  1204. multiple integration. (If var is omitted and the integrand is
  1205. univariate, the indefinite integral in that variable will be performed.)
  1206. Indefinite integrals are returned without terms that are independent
  1207. of the integration variables. (see examples)
  1208. Definite improper integrals often entail delicate convergence
  1209. conditions. Pass conds='piecewise', 'separate' or 'none' to have
  1210. these returned, respectively, as a Piecewise function, as a separate
  1211. result (i.e. result will be a tuple), or not at all (default is
  1212. 'piecewise').
  1213. **Strategy**
  1214. SymPy uses various approaches to definite integration. One method is to
  1215. find an antiderivative for the integrand, and then use the fundamental
  1216. theorem of calculus. Various functions are implemented to integrate
  1217. polynomial, rational and trigonometric functions, and integrands
  1218. containing DiracDelta terms.
  1219. SymPy also implements the part of the Risch algorithm, which is a decision
  1220. procedure for integrating elementary functions, i.e., the algorithm can
  1221. either find an elementary antiderivative, or prove that one does not
  1222. exist. There is also a (very successful, albeit somewhat slow) general
  1223. implementation of the heuristic Risch algorithm. This algorithm will
  1224. eventually be phased out as more of the full Risch algorithm is
  1225. implemented. See the docstring of Integral._eval_integral() for more
  1226. details on computing the antiderivative using algebraic methods.
  1227. The option risch=True can be used to use only the (full) Risch algorithm.
  1228. This is useful if you want to know if an elementary function has an
  1229. elementary antiderivative. If the indefinite Integral returned by this
  1230. function is an instance of NonElementaryIntegral, that means that the
  1231. Risch algorithm has proven that integral to be non-elementary. Note that
  1232. by default, additional methods (such as the Meijer G method outlined
  1233. below) are tried on these integrals, as they may be expressible in terms
  1234. of special functions, so if you only care about elementary answers, use
  1235. risch=True. Also note that an unevaluated Integral returned by this
  1236. function is not necessarily a NonElementaryIntegral, even with risch=True,
  1237. as it may just be an indication that the particular part of the Risch
  1238. algorithm needed to integrate that function is not yet implemented.
  1239. Another family of strategies comes from re-writing the integrand in
  1240. terms of so-called Meijer G-functions. Indefinite integrals of a
  1241. single G-function can always be computed, and the definite integral
  1242. of a product of two G-functions can be computed from zero to
  1243. infinity. Various strategies are implemented to rewrite integrands
  1244. as G-functions, and use this information to compute integrals (see
  1245. the ``meijerint`` module).
  1246. The option manual=True can be used to use only an algorithm that tries
  1247. to mimic integration by hand. This algorithm does not handle as many
  1248. integrands as the other algorithms implemented but may return results in
  1249. a more familiar form. The ``manualintegrate`` module has functions that
  1250. return the steps used (see the module docstring for more information).
  1251. In general, the algebraic methods work best for computing
  1252. antiderivatives of (possibly complicated) combinations of elementary
  1253. functions. The G-function methods work best for computing definite
  1254. integrals from zero to infinity of moderately complicated
  1255. combinations of special functions, or indefinite integrals of very
  1256. simple combinations of special functions.
  1257. The strategy employed by the integration code is as follows:
  1258. - If computing a definite integral, and both limits are real,
  1259. and at least one limit is +- oo, try the G-function method of
  1260. definite integration first.
  1261. - Try to find an antiderivative, using all available methods, ordered
  1262. by performance (that is try fastest method first, slowest last; in
  1263. particular polynomial integration is tried first, Meijer
  1264. G-functions second to last, and heuristic Risch last).
  1265. - If still not successful, try G-functions irrespective of the
  1266. limits.
  1267. The option meijerg=True, False, None can be used to, respectively:
  1268. always use G-function methods and no others, never use G-function
  1269. methods, or use all available methods (in order as described above).
  1270. It defaults to None.
  1271. Examples
  1272. ========
  1273. >>> from sympy import integrate, log, exp, oo
  1274. >>> from sympy.abc import a, x, y
  1275. >>> integrate(x*y, x)
  1276. x**2*y/2
  1277. >>> integrate(log(x), x)
  1278. x*log(x) - x
  1279. >>> integrate(log(x), (x, 1, a))
  1280. a*log(a) - a + 1
  1281. >>> integrate(x)
  1282. x**2/2
  1283. Terms that are independent of x are dropped by indefinite integration:
  1284. >>> from sympy import sqrt
  1285. >>> integrate(sqrt(1 + x), (x, 0, x))
  1286. 2*(x + 1)**(3/2)/3 - 2/3
  1287. >>> integrate(sqrt(1 + x), x)
  1288. 2*(x + 1)**(3/2)/3
  1289. >>> integrate(x*y)
  1290. Traceback (most recent call last):
  1291. ...
  1292. ValueError: specify integration variables to integrate x*y
  1293. Note that ``integrate(x)`` syntax is meant only for convenience
  1294. in interactive sessions and should be avoided in library code.
  1295. >>> integrate(x**a*exp(-x), (x, 0, oo)) # same as conds='piecewise'
  1296. Piecewise((gamma(a + 1), re(a) > -1),
  1297. (Integral(x**a*exp(-x), (x, 0, oo)), True))
  1298. >>> integrate(x**a*exp(-x), (x, 0, oo), conds='none')
  1299. gamma(a + 1)
  1300. >>> integrate(x**a*exp(-x), (x, 0, oo), conds='separate')
  1301. (gamma(a + 1), re(a) > -1)
  1302. See Also
  1303. ========
  1304. Integral, Integral.doit
  1305. """
  1306. doit_flags = {
  1307. 'deep': False,
  1308. 'meijerg': meijerg,
  1309. 'conds': conds,
  1310. 'risch': risch,
  1311. 'heurisch': heurisch,
  1312. 'manual': manual
  1313. }
  1314. integral = Integral(*args, **kwargs)
  1315. if isinstance(integral, Integral):
  1316. return integral.doit(**doit_flags)
  1317. else:
  1318. new_args = [a.doit(**doit_flags) if isinstance(a, Integral) else a
  1319. for a in integral.args]
  1320. return integral.func(*new_args)
  1321. def line_integrate(field, curve, vars):
  1322. """line_integrate(field, Curve, variables)
  1323. Compute the line integral.
  1324. Examples
  1325. ========
  1326. >>> from sympy import Curve, line_integrate, E, ln
  1327. >>> from sympy.abc import x, y, t
  1328. >>> C = Curve([E**t + 1, E**t - 1], (t, 0, ln(2)))
  1329. >>> line_integrate(x + y, C, [x, y])
  1330. 3*sqrt(2)
  1331. See Also
  1332. ========
  1333. sympy.integrals.integrals.integrate, Integral
  1334. """
  1335. from sympy.geometry import Curve
  1336. F = sympify(field)
  1337. if not F:
  1338. raise ValueError(
  1339. "Expecting function specifying field as first argument.")
  1340. if not isinstance(curve, Curve):
  1341. raise ValueError("Expecting Curve entity as second argument.")
  1342. if not is_sequence(vars):
  1343. raise ValueError("Expecting ordered iterable for variables.")
  1344. if len(curve.functions) != len(vars):
  1345. raise ValueError("Field variable size does not match curve dimension.")
  1346. if curve.parameter in vars:
  1347. raise ValueError("Curve parameter clashes with field parameters.")
  1348. # Calculate derivatives for line parameter functions
  1349. # F(r) -> F(r(t)) and finally F(r(t)*r'(t))
  1350. Ft = F
  1351. dldt = 0
  1352. for i, var in enumerate(vars):
  1353. _f = curve.functions[i]
  1354. _dn = diff(_f, curve.parameter)
  1355. # ...arc length
  1356. dldt = dldt + (_dn * _dn)
  1357. Ft = Ft.subs(var, _f)
  1358. Ft = Ft * sqrt(dldt)
  1359. integral = Integral(Ft, curve.limits).doit(deep=False)
  1360. return integral
  1361. ### Property function dispatching ###
  1362. @shape.register(Integral)
  1363. def _(expr):
  1364. return shape(expr.function)
  1365. # Delayed imports
  1366. from .deltafunctions import deltaintegrate
  1367. from .meijerint import meijerint_definite, meijerint_indefinite, _debug
  1368. from .trigonometry import trigintegrate