integrals.py 63 KB

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