integrals.py 63 KB

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