summations.py 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615
  1. from typing import Tuple as tTuple
  2. from sympy.calculus.singularities import is_decreasing
  3. from sympy.calculus.accumulationbounds import AccumulationBounds
  4. from .expr_with_intlimits import ExprWithIntLimits
  5. from .expr_with_limits import AddWithLimits
  6. from .gosper import gosper_sum
  7. from sympy.core.expr import Expr
  8. from sympy.core.add import Add
  9. from sympy.core.containers import Tuple
  10. from sympy.core.function import Derivative, expand
  11. from sympy.core.mul import Mul
  12. from sympy.core.numbers import Float
  13. from sympy.core.relational import Eq
  14. from sympy.core.singleton import S
  15. from sympy.core.sorting import ordered
  16. from sympy.core.symbol import Dummy, Wild, Symbol, symbols
  17. from sympy.functions.combinatorial.factorials import factorial
  18. from sympy.functions.combinatorial.numbers import bernoulli, harmonic
  19. from sympy.functions.elementary.exponential import exp, log
  20. from sympy.functions.elementary.piecewise import Piecewise
  21. from sympy.functions.elementary.trigonometric import cot, csc
  22. from sympy.functions.special.hyper import hyper
  23. from sympy.functions.special.tensor_functions import KroneckerDelta
  24. from sympy.functions.special.zeta_functions import zeta
  25. from sympy.integrals.integrals import Integral
  26. from sympy.logic.boolalg import And
  27. from sympy.polys.partfrac import apart
  28. from sympy.polys.polyerrors import PolynomialError, PolificationFailed
  29. from sympy.polys.polytools import parallel_poly_from_expr, Poly, factor
  30. from sympy.polys.rationaltools import together
  31. from sympy.series.limitseq import limit_seq
  32. from sympy.series.order import O
  33. from sympy.series.residues import residue
  34. from sympy.sets.sets import FiniteSet, Interval
  35. from sympy.simplify.combsimp import combsimp
  36. from sympy.simplify.hyperexpand import hyperexpand
  37. from sympy.simplify.powsimp import powsimp
  38. from sympy.simplify.radsimp import denom, fraction
  39. from sympy.simplify.simplify import (factor_sum, sum_combine, simplify,
  40. nsimplify, hypersimp)
  41. from sympy.solvers.solvers import solve
  42. from sympy.solvers.solveset import solveset
  43. from sympy.utilities.iterables import sift
  44. import itertools
  45. class Sum(AddWithLimits, ExprWithIntLimits):
  46. r"""
  47. Represents unevaluated summation.
  48. Explanation
  49. ===========
  50. ``Sum`` represents a finite or infinite series, with the first argument
  51. being the general form of terms in the series, and the second argument
  52. being ``(dummy_variable, start, end)``, with ``dummy_variable`` taking
  53. all integer values from ``start`` through ``end``. In accordance with
  54. long-standing mathematical convention, the end term is included in the
  55. summation.
  56. Finite sums
  57. ===========
  58. For finite sums (and sums with symbolic limits assumed to be finite) we
  59. follow the summation convention described by Karr [1], especially
  60. definition 3 of section 1.4. The sum:
  61. .. math::
  62. \sum_{m \leq i < n} f(i)
  63. has *the obvious meaning* for `m < n`, namely:
  64. .. math::
  65. \sum_{m \leq i < n} f(i) = f(m) + f(m+1) + \ldots + f(n-2) + f(n-1)
  66. with the upper limit value `f(n)` excluded. The sum over an empty set is
  67. zero if and only if `m = n`:
  68. .. math::
  69. \sum_{m \leq i < n} f(i) = 0 \quad \mathrm{for} \quad m = n
  70. Finally, for all other sums over empty sets we assume the following
  71. definition:
  72. .. math::
  73. \sum_{m \leq i < n} f(i) = - \sum_{n \leq i < m} f(i) \quad \mathrm{for} \quad m > n
  74. It is important to note that Karr defines all sums with the upper
  75. limit being exclusive. This is in contrast to the usual mathematical notation,
  76. but does not affect the summation convention. Indeed we have:
  77. .. math::
  78. \sum_{m \leq i < n} f(i) = \sum_{i = m}^{n - 1} f(i)
  79. where the difference in notation is intentional to emphasize the meaning,
  80. with limits typeset on the top being inclusive.
  81. Examples
  82. ========
  83. >>> from sympy.abc import i, k, m, n, x
  84. >>> from sympy import Sum, factorial, oo, IndexedBase, Function
  85. >>> Sum(k, (k, 1, m))
  86. Sum(k, (k, 1, m))
  87. >>> Sum(k, (k, 1, m)).doit()
  88. m**2/2 + m/2
  89. >>> Sum(k**2, (k, 1, m))
  90. Sum(k**2, (k, 1, m))
  91. >>> Sum(k**2, (k, 1, m)).doit()
  92. m**3/3 + m**2/2 + m/6
  93. >>> Sum(x**k, (k, 0, oo))
  94. Sum(x**k, (k, 0, oo))
  95. >>> Sum(x**k, (k, 0, oo)).doit()
  96. Piecewise((1/(1 - x), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True))
  97. >>> Sum(x**k/factorial(k), (k, 0, oo)).doit()
  98. exp(x)
  99. Here are examples to do summation with symbolic indices. You
  100. can use either Function of IndexedBase classes:
  101. >>> f = Function('f')
  102. >>> Sum(f(n), (n, 0, 3)).doit()
  103. f(0) + f(1) + f(2) + f(3)
  104. >>> Sum(f(n), (n, 0, oo)).doit()
  105. Sum(f(n), (n, 0, oo))
  106. >>> f = IndexedBase('f')
  107. >>> Sum(f[n]**2, (n, 0, 3)).doit()
  108. f[0]**2 + f[1]**2 + f[2]**2 + f[3]**2
  109. An example showing that the symbolic result of a summation is still
  110. valid for seemingly nonsensical values of the limits. Then the Karr
  111. convention allows us to give a perfectly valid interpretation to
  112. those sums by interchanging the limits according to the above rules:
  113. >>> S = Sum(i, (i, 1, n)).doit()
  114. >>> S
  115. n**2/2 + n/2
  116. >>> S.subs(n, -4)
  117. 6
  118. >>> Sum(i, (i, 1, -4)).doit()
  119. 6
  120. >>> Sum(-i, (i, -3, 0)).doit()
  121. 6
  122. An explicit example of the Karr summation convention:
  123. >>> S1 = Sum(i**2, (i, m, m+n-1)).doit()
  124. >>> S1
  125. m**2*n + m*n**2 - m*n + n**3/3 - n**2/2 + n/6
  126. >>> S2 = Sum(i**2, (i, m+n, m-1)).doit()
  127. >>> S2
  128. -m**2*n - m*n**2 + m*n - n**3/3 + n**2/2 - n/6
  129. >>> S1 + S2
  130. 0
  131. >>> S3 = Sum(i, (i, m, m-1)).doit()
  132. >>> S3
  133. 0
  134. See Also
  135. ========
  136. summation
  137. Product, sympy.concrete.products.product
  138. References
  139. ==========
  140. .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
  141. Volume 28 Issue 2, April 1981, Pages 305-350
  142. http://dl.acm.org/citation.cfm?doid=322248.322255
  143. .. [2] https://en.wikipedia.org/wiki/Summation#Capital-sigma_notation
  144. .. [3] https://en.wikipedia.org/wiki/Empty_sum
  145. """
  146. __slots__ = ('is_commutative',)
  147. limits: tTuple[tTuple[Symbol, Expr, Expr]]
  148. def __new__(cls, function, *symbols, **assumptions):
  149. obj = AddWithLimits.__new__(cls, function, *symbols, **assumptions)
  150. if not hasattr(obj, 'limits'):
  151. return obj
  152. if any(len(l) != 3 or None in l for l in obj.limits):
  153. raise ValueError('Sum requires values for lower and upper bounds.')
  154. return obj
  155. def _eval_is_zero(self):
  156. # a Sum is only zero if its function is zero or if all terms
  157. # cancel out. This only answers whether the summand is zero; if
  158. # not then None is returned since we don't analyze whether all
  159. # terms cancel out.
  160. if self.function.is_zero or self.has_empty_sequence:
  161. return True
  162. def _eval_is_extended_real(self):
  163. if self.has_empty_sequence:
  164. return True
  165. return self.function.is_extended_real
  166. def _eval_is_positive(self):
  167. if self.has_finite_limits and self.has_reversed_limits is False:
  168. return self.function.is_positive
  169. def _eval_is_negative(self):
  170. if self.has_finite_limits and self.has_reversed_limits is False:
  171. return self.function.is_negative
  172. def _eval_is_finite(self):
  173. if self.has_finite_limits and self.function.is_finite:
  174. return True
  175. def doit(self, **hints):
  176. if hints.get('deep', True):
  177. f = self.function.doit(**hints)
  178. else:
  179. f = self.function
  180. # first make sure any definite limits have summation
  181. # variables with matching assumptions
  182. reps = {}
  183. for xab in self.limits:
  184. d = _dummy_with_inherited_properties_concrete(xab)
  185. if d:
  186. reps[xab[0]] = d
  187. if reps:
  188. undo = {v: k for k, v in reps.items()}
  189. did = self.xreplace(reps).doit(**hints)
  190. if isinstance(did, tuple): # when separate=True
  191. did = tuple([i.xreplace(undo) for i in did])
  192. elif did is not None:
  193. did = did.xreplace(undo)
  194. else:
  195. did = self
  196. return did
  197. if self.function.is_Matrix:
  198. expanded = self.expand()
  199. if self != expanded:
  200. return expanded.doit()
  201. return _eval_matrix_sum(self)
  202. for n, limit in enumerate(self.limits):
  203. i, a, b = limit
  204. dif = b - a
  205. if dif == -1:
  206. # Any summation over an empty set is zero
  207. return S.Zero
  208. if dif.is_integer and dif.is_negative:
  209. a, b = b + 1, a - 1
  210. f = -f
  211. newf = eval_sum(f, (i, a, b))
  212. if newf is None:
  213. if f == self.function:
  214. zeta_function = self.eval_zeta_function(f, (i, a, b))
  215. if zeta_function is not None:
  216. return zeta_function
  217. return self
  218. else:
  219. return self.func(f, *self.limits[n:])
  220. f = newf
  221. if hints.get('deep', True):
  222. # eval_sum could return partially unevaluated
  223. # result with Piecewise. In this case we won't
  224. # doit() recursively.
  225. if not isinstance(f, Piecewise):
  226. return f.doit(**hints)
  227. return f
  228. def eval_zeta_function(self, f, limits):
  229. """
  230. Check whether the function matches with the zeta function.
  231. If it matches, then return a `Piecewise` expression because
  232. zeta function does not converge unless `s > 1` and `q > 0`
  233. """
  234. i, a, b = limits
  235. w, y, z = Wild('w', exclude=[i]), Wild('y', exclude=[i]), Wild('z', exclude=[i])
  236. result = f.match((w * i + y) ** (-z))
  237. if result is not None and b is S.Infinity:
  238. coeff = 1 / result[w] ** result[z]
  239. s = result[z]
  240. q = result[y] / result[w] + a
  241. return Piecewise((coeff * zeta(s, q), And(q > 0, s > 1)), (self, True))
  242. def _eval_derivative(self, x):
  243. """
  244. Differentiate wrt x as long as x is not in the free symbols of any of
  245. the upper or lower limits.
  246. Explanation
  247. ===========
  248. Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a`
  249. since the value of the sum is discontinuous in `a`. In a case
  250. involving a limit variable, the unevaluated derivative is returned.
  251. """
  252. # diff already confirmed that x is in the free symbols of self, but we
  253. # don't want to differentiate wrt any free symbol in the upper or lower
  254. # limits
  255. # XXX remove this test for free_symbols when the default _eval_derivative is in
  256. if isinstance(x, Symbol) and x not in self.free_symbols:
  257. return S.Zero
  258. # get limits and the function
  259. f, limits = self.function, list(self.limits)
  260. limit = limits.pop(-1)
  261. if limits: # f is the argument to a Sum
  262. f = self.func(f, *limits)
  263. _, a, b = limit
  264. if x in a.free_symbols or x in b.free_symbols:
  265. return None
  266. df = Derivative(f, x, evaluate=True)
  267. rv = self.func(df, limit)
  268. return rv
  269. def _eval_difference_delta(self, n, step):
  270. k, _, upper = self.args[-1]
  271. new_upper = upper.subs(n, n + step)
  272. if len(self.args) == 2:
  273. f = self.args[0]
  274. else:
  275. f = self.func(*self.args[:-1])
  276. return Sum(f, (k, upper + 1, new_upper)).doit()
  277. def _eval_simplify(self, **kwargs):
  278. # split the function into adds
  279. terms = Add.make_args(expand(self.function))
  280. s_t = [] # Sum Terms
  281. o_t = [] # Other Terms
  282. for term in terms:
  283. if term.has(Sum):
  284. # if there is an embedded sum here
  285. # it is of the form x * (Sum(whatever))
  286. # hence we make a Mul out of it, and simplify all interior sum terms
  287. subterms = Mul.make_args(expand(term))
  288. out_terms = []
  289. for subterm in subterms:
  290. # go through each term
  291. if isinstance(subterm, Sum):
  292. # if it's a sum, simplify it
  293. out_terms.append(subterm._eval_simplify())
  294. else:
  295. # otherwise, add it as is
  296. out_terms.append(subterm)
  297. # turn it back into a Mul
  298. s_t.append(Mul(*out_terms))
  299. else:
  300. o_t.append(term)
  301. # next try to combine any interior sums for further simplification
  302. result = Add(sum_combine(s_t), *o_t)
  303. return factor_sum(result, limits=self.limits)
  304. def is_convergent(self):
  305. r"""
  306. Checks for the convergence of a Sum.
  307. Explanation
  308. ===========
  309. We divide the study of convergence of infinite sums and products in
  310. two parts.
  311. First Part:
  312. One part is the question whether all the terms are well defined, i.e.,
  313. they are finite in a sum and also non-zero in a product. Zero
  314. is the analogy of (minus) infinity in products as
  315. :math:`e^{-\infty} = 0`.
  316. Second Part:
  317. The second part is the question of convergence after infinities,
  318. and zeros in products, have been omitted assuming that their number
  319. is finite. This means that we only consider the tail of the sum or
  320. product, starting from some point after which all terms are well
  321. defined.
  322. For example, in a sum of the form:
  323. .. math::
  324. \sum_{1 \leq i < \infty} \frac{1}{n^2 + an + b}
  325. where a and b are numbers. The routine will return true, even if there
  326. are infinities in the term sequence (at most two). An analogous
  327. product would be:
  328. .. math::
  329. \prod_{1 \leq i < \infty} e^{\frac{1}{n^2 + an + b}}
  330. This is how convergence is interpreted. It is concerned with what
  331. happens at the limit. Finding the bad terms is another independent
  332. matter.
  333. Note: It is responsibility of user to see that the sum or product
  334. is well defined.
  335. There are various tests employed to check the convergence like
  336. divergence test, root test, integral test, alternating series test,
  337. comparison tests, Dirichlet tests. It returns true if Sum is convergent
  338. and false if divergent and NotImplementedError if it cannot be checked.
  339. References
  340. ==========
  341. .. [1] https://en.wikipedia.org/wiki/Convergence_tests
  342. Examples
  343. ========
  344. >>> from sympy import factorial, S, Sum, Symbol, oo
  345. >>> n = Symbol('n', integer=True)
  346. >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent()
  347. True
  348. >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent()
  349. False
  350. >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent()
  351. False
  352. >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent()
  353. True
  354. See Also
  355. ========
  356. Sum.is_absolutely_convergent()
  357. sympy.concrete.products.Product.is_convergent()
  358. """
  359. p, q, r = symbols('p q r', cls=Wild)
  360. sym = self.limits[0][0]
  361. lower_limit = self.limits[0][1]
  362. upper_limit = self.limits[0][2]
  363. sequence_term = self.function.simplify()
  364. if len(sequence_term.free_symbols) > 1:
  365. raise NotImplementedError("convergence checking for more than one symbol "
  366. "containing series is not handled")
  367. if lower_limit.is_finite and upper_limit.is_finite:
  368. return S.true
  369. # transform sym -> -sym and swap the upper_limit = S.Infinity
  370. # and lower_limit = - upper_limit
  371. if lower_limit is S.NegativeInfinity:
  372. if upper_limit is S.Infinity:
  373. return Sum(sequence_term, (sym, 0, S.Infinity)).is_convergent() and \
  374. Sum(sequence_term, (sym, S.NegativeInfinity, 0)).is_convergent()
  375. sequence_term = simplify(sequence_term.xreplace({sym: -sym}))
  376. lower_limit = -upper_limit
  377. upper_limit = S.Infinity
  378. sym_ = Dummy(sym.name, integer=True, positive=True)
  379. sequence_term = sequence_term.xreplace({sym: sym_})
  380. sym = sym_
  381. interval = Interval(lower_limit, upper_limit)
  382. # Piecewise function handle
  383. if sequence_term.is_Piecewise:
  384. for func, cond in sequence_term.args:
  385. # see if it represents something going to oo
  386. if cond == True or cond.as_set().sup is S.Infinity:
  387. s = Sum(func, (sym, lower_limit, upper_limit))
  388. return s.is_convergent()
  389. return S.true
  390. ### -------- Divergence test ----------- ###
  391. try:
  392. lim_val = limit_seq(sequence_term, sym)
  393. if lim_val is not None and lim_val.is_zero is False:
  394. return S.false
  395. except NotImplementedError:
  396. pass
  397. try:
  398. lim_val_abs = limit_seq(abs(sequence_term), sym)
  399. if lim_val_abs is not None and lim_val_abs.is_zero is False:
  400. return S.false
  401. except NotImplementedError:
  402. pass
  403. order = O(sequence_term, (sym, S.Infinity))
  404. ### --------- p-series test (1/n**p) ---------- ###
  405. p_series_test = order.expr.match(sym**p)
  406. if p_series_test is not None:
  407. if p_series_test[p] < -1:
  408. return S.true
  409. if p_series_test[p] >= -1:
  410. return S.false
  411. ### ------------- comparison test ------------- ###
  412. # 1/(n**p*log(n)**q*log(log(n))**r) comparison
  413. n_log_test = order.expr.match(1/(sym**p*log(sym)**q*log(log(sym))**r))
  414. if n_log_test is not None:
  415. if (n_log_test[p] > 1 or
  416. (n_log_test[p] == 1 and n_log_test[q] > 1) or
  417. (n_log_test[p] == n_log_test[q] == 1 and n_log_test[r] > 1)):
  418. return S.true
  419. return S.false
  420. ### ------------- Limit comparison test -----------###
  421. # (1/n) comparison
  422. try:
  423. lim_comp = limit_seq(sym*sequence_term, sym)
  424. if lim_comp is not None and lim_comp.is_number and lim_comp > 0:
  425. return S.false
  426. except NotImplementedError:
  427. pass
  428. ### ----------- ratio test ---------------- ###
  429. next_sequence_term = sequence_term.xreplace({sym: sym + 1})
  430. ratio = combsimp(powsimp(next_sequence_term/sequence_term))
  431. try:
  432. lim_ratio = limit_seq(ratio, sym)
  433. if lim_ratio is not None and lim_ratio.is_number:
  434. if abs(lim_ratio) > 1:
  435. return S.false
  436. if abs(lim_ratio) < 1:
  437. return S.true
  438. except NotImplementedError:
  439. lim_ratio = None
  440. ### ---------- Raabe's test -------------- ###
  441. if lim_ratio == 1: # ratio test inconclusive
  442. test_val = sym*(sequence_term/
  443. sequence_term.subs(sym, sym + 1) - 1)
  444. test_val = test_val.gammasimp()
  445. try:
  446. lim_val = limit_seq(test_val, sym)
  447. if lim_val is not None and lim_val.is_number:
  448. if lim_val > 1:
  449. return S.true
  450. if lim_val < 1:
  451. return S.false
  452. except NotImplementedError:
  453. pass
  454. ### ----------- root test ---------------- ###
  455. # lim = Limit(abs(sequence_term)**(1/sym), sym, S.Infinity)
  456. try:
  457. lim_evaluated = limit_seq(abs(sequence_term)**(1/sym), sym)
  458. if lim_evaluated is not None and lim_evaluated.is_number:
  459. if lim_evaluated < 1:
  460. return S.true
  461. if lim_evaluated > 1:
  462. return S.false
  463. except NotImplementedError:
  464. pass
  465. ### ------------- alternating series test ----------- ###
  466. dict_val = sequence_term.match(S.NegativeOne**(sym + p)*q)
  467. if not dict_val[p].has(sym) and is_decreasing(dict_val[q], interval):
  468. return S.true
  469. ### ------------- integral test -------------- ###
  470. check_interval = None
  471. maxima = solveset(sequence_term.diff(sym), sym, interval)
  472. if not maxima:
  473. check_interval = interval
  474. elif isinstance(maxima, FiniteSet) and maxima.sup.is_number:
  475. check_interval = Interval(maxima.sup, interval.sup)
  476. if (check_interval is not None and
  477. (is_decreasing(sequence_term, check_interval) or
  478. is_decreasing(-sequence_term, check_interval))):
  479. integral_val = Integral(
  480. sequence_term, (sym, lower_limit, upper_limit))
  481. try:
  482. integral_val_evaluated = integral_val.doit()
  483. if integral_val_evaluated.is_number:
  484. return S(integral_val_evaluated.is_finite)
  485. except NotImplementedError:
  486. pass
  487. ### ----- Dirichlet and bounded times convergent tests ----- ###
  488. # TODO
  489. #
  490. # Dirichlet_test
  491. # https://en.wikipedia.org/wiki/Dirichlet%27s_test
  492. #
  493. # Bounded times convergent test
  494. # It is based on comparison theorems for series.
  495. # In particular, if the general term of a series can
  496. # be written as a product of two terms a_n and b_n
  497. # and if a_n is bounded and if Sum(b_n) is absolutely
  498. # convergent, then the original series Sum(a_n * b_n)
  499. # is absolutely convergent and so convergent.
  500. #
  501. # The following code can grows like 2**n where n is the
  502. # number of args in order.expr
  503. # Possibly combined with the potentially slow checks
  504. # inside the loop, could make this test extremely slow
  505. # for larger summation expressions.
  506. if order.expr.is_Mul:
  507. args = order.expr.args
  508. argset = set(args)
  509. ### -------------- Dirichlet tests -------------- ###
  510. m = Dummy('m', integer=True)
  511. def _dirichlet_test(g_n):
  512. try:
  513. ing_val = limit_seq(Sum(g_n, (sym, interval.inf, m)).doit(), m)
  514. if ing_val is not None and ing_val.is_finite:
  515. return S.true
  516. except NotImplementedError:
  517. pass
  518. ### -------- bounded times convergent test ---------###
  519. def _bounded_convergent_test(g1_n, g2_n):
  520. try:
  521. lim_val = limit_seq(g1_n, sym)
  522. if lim_val is not None and (lim_val.is_finite or (
  523. isinstance(lim_val, AccumulationBounds)
  524. and (lim_val.max - lim_val.min).is_finite)):
  525. if Sum(g2_n, (sym, lower_limit, upper_limit)).is_absolutely_convergent():
  526. return S.true
  527. except NotImplementedError:
  528. pass
  529. for n in range(1, len(argset)):
  530. for a_tuple in itertools.combinations(args, n):
  531. b_set = argset - set(a_tuple)
  532. a_n = Mul(*a_tuple)
  533. b_n = Mul(*b_set)
  534. if is_decreasing(a_n, interval):
  535. dirich = _dirichlet_test(b_n)
  536. if dirich is not None:
  537. return dirich
  538. bc_test = _bounded_convergent_test(a_n, b_n)
  539. if bc_test is not None:
  540. return bc_test
  541. _sym = self.limits[0][0]
  542. sequence_term = sequence_term.xreplace({sym: _sym})
  543. raise NotImplementedError("The algorithm to find the Sum convergence of %s "
  544. "is not yet implemented" % (sequence_term))
  545. def is_absolutely_convergent(self):
  546. """
  547. Checks for the absolute convergence of an infinite series.
  548. Same as checking convergence of absolute value of sequence_term of
  549. an infinite series.
  550. References
  551. ==========
  552. .. [1] https://en.wikipedia.org/wiki/Absolute_convergence
  553. Examples
  554. ========
  555. >>> from sympy import Sum, Symbol, oo
  556. >>> n = Symbol('n', integer=True)
  557. >>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent()
  558. False
  559. >>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent()
  560. True
  561. See Also
  562. ========
  563. Sum.is_convergent()
  564. """
  565. return Sum(abs(self.function), self.limits).is_convergent()
  566. def euler_maclaurin(self, m=0, n=0, eps=0, eval_integral=True):
  567. """
  568. Return an Euler-Maclaurin approximation of self, where m is the
  569. number of leading terms to sum directly and n is the number of
  570. terms in the tail.
  571. With m = n = 0, this is simply the corresponding integral
  572. plus a first-order endpoint correction.
  573. Returns (s, e) where s is the Euler-Maclaurin approximation
  574. and e is the estimated error (taken to be the magnitude of
  575. the first omitted term in the tail):
  576. >>> from sympy.abc import k, a, b
  577. >>> from sympy import Sum
  578. >>> Sum(1/k, (k, 2, 5)).doit().evalf()
  579. 1.28333333333333
  580. >>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin()
  581. >>> s
  582. -log(2) + 7/20 + log(5)
  583. >>> from sympy import sstr
  584. >>> print(sstr((s.evalf(), e.evalf()), full_prec=True))
  585. (1.26629073187415, 0.0175000000000000)
  586. The endpoints may be symbolic:
  587. >>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin()
  588. >>> s
  589. -log(a) + log(b) + 1/(2*b) + 1/(2*a)
  590. >>> e
  591. Abs(1/(12*b**2) - 1/(12*a**2))
  592. If the function is a polynomial of degree at most 2n+1, the
  593. Euler-Maclaurin formula becomes exact (and e = 0 is returned):
  594. >>> Sum(k, (k, 2, b)).euler_maclaurin()
  595. (b**2/2 + b/2 - 1, 0)
  596. >>> Sum(k, (k, 2, b)).doit()
  597. b**2/2 + b/2 - 1
  598. With a nonzero eps specified, the summation is ended
  599. as soon as the remainder term is less than the epsilon.
  600. """
  601. m = int(m)
  602. n = int(n)
  603. f = self.function
  604. if len(self.limits) != 1:
  605. raise ValueError("More than 1 limit")
  606. i, a, b = self.limits[0]
  607. if (a > b) == True:
  608. if a - b == 1:
  609. return S.Zero, S.Zero
  610. a, b = b + 1, a - 1
  611. f = -f
  612. s = S.Zero
  613. if m:
  614. if b.is_Integer and a.is_Integer:
  615. m = min(m, b - a + 1)
  616. if not eps or f.is_polynomial(i):
  617. for k in range(m):
  618. s += f.subs(i, a + k)
  619. else:
  620. term = f.subs(i, a)
  621. if term:
  622. test = abs(term.evalf(3)) < eps
  623. if test == True:
  624. return s, abs(term)
  625. elif not (test == False):
  626. # a symbolic Relational class, can't go further
  627. return term, S.Zero
  628. s += term
  629. for k in range(1, m):
  630. term = f.subs(i, a + k)
  631. if abs(term.evalf(3)) < eps and term != 0:
  632. return s, abs(term)
  633. s += term
  634. if b - a + 1 == m:
  635. return s, S.Zero
  636. a += m
  637. x = Dummy('x')
  638. I = Integral(f.subs(i, x), (x, a, b))
  639. if eval_integral:
  640. I = I.doit()
  641. s += I
  642. def fpoint(expr):
  643. if b is S.Infinity:
  644. return expr.subs(i, a), 0
  645. return expr.subs(i, a), expr.subs(i, b)
  646. fa, fb = fpoint(f)
  647. iterm = (fa + fb)/2
  648. g = f.diff(i)
  649. for k in range(1, n + 2):
  650. ga, gb = fpoint(g)
  651. term = bernoulli(2*k)/factorial(2*k)*(gb - ga)
  652. if k > n:
  653. break
  654. if eps and term:
  655. term_evalf = term.evalf(3)
  656. if term_evalf is S.NaN:
  657. return S.NaN, S.NaN
  658. if abs(term_evalf) < eps:
  659. break
  660. s += term
  661. g = g.diff(i, 2, simplify=False)
  662. return s + iterm, abs(term)
  663. def reverse_order(self, *indices):
  664. """
  665. Reverse the order of a limit in a Sum.
  666. Explanation
  667. ===========
  668. ``reverse_order(self, *indices)`` reverses some limits in the expression
  669. ``self`` which can be either a ``Sum`` or a ``Product``. The selectors in
  670. the argument ``indices`` specify some indices whose limits get reversed.
  671. These selectors are either variable names or numerical indices counted
  672. starting from the inner-most limit tuple.
  673. Examples
  674. ========
  675. >>> from sympy import Sum
  676. >>> from sympy.abc import x, y, a, b, c, d
  677. >>> Sum(x, (x, 0, 3)).reverse_order(x)
  678. Sum(-x, (x, 4, -1))
  679. >>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y)
  680. Sum(x*y, (x, 6, 0), (y, 7, -1))
  681. >>> Sum(x, (x, a, b)).reverse_order(x)
  682. Sum(-x, (x, b + 1, a - 1))
  683. >>> Sum(x, (x, a, b)).reverse_order(0)
  684. Sum(-x, (x, b + 1, a - 1))
  685. While one should prefer variable names when specifying which limits
  686. to reverse, the index counting notation comes in handy in case there
  687. are several symbols with the same name.
  688. >>> S = Sum(x**2, (x, a, b), (x, c, d))
  689. >>> S
  690. Sum(x**2, (x, a, b), (x, c, d))
  691. >>> S0 = S.reverse_order(0)
  692. >>> S0
  693. Sum(-x**2, (x, b + 1, a - 1), (x, c, d))
  694. >>> S1 = S0.reverse_order(1)
  695. >>> S1
  696. Sum(x**2, (x, b + 1, a - 1), (x, d + 1, c - 1))
  697. Of course we can mix both notations:
  698. >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1)
  699. Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
  700. >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x)
  701. Sum(x*y, (x, b + 1, a - 1), (y, 6, 1))
  702. See Also
  703. ========
  704. sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index, reorder_limit,
  705. sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder
  706. References
  707. ==========
  708. .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM,
  709. Volume 28 Issue 2, April 1981, Pages 305-350
  710. http://dl.acm.org/citation.cfm?doid=322248.322255
  711. """
  712. l_indices = list(indices)
  713. for i, indx in enumerate(l_indices):
  714. if not isinstance(indx, int):
  715. l_indices[i] = self.index(indx)
  716. e = 1
  717. limits = []
  718. for i, limit in enumerate(self.limits):
  719. l = limit
  720. if i in l_indices:
  721. e = -e
  722. l = (limit[0], limit[2] + 1, limit[1] - 1)
  723. limits.append(l)
  724. return Sum(e * self.function, *limits)
  725. def _eval_rewrite_as_Product(self, *args, **kwargs):
  726. from sympy.concrete.products import Product
  727. if self.function.is_extended_real:
  728. return log(Product(exp(self.function), *self.limits))
  729. def summation(f, *symbols, **kwargs):
  730. r"""
  731. Compute the summation of f with respect to symbols.
  732. Explanation
  733. ===========
  734. The notation for symbols is similar to the notation used in Integral.
  735. summation(f, (i, a, b)) computes the sum of f with respect to i from a to b,
  736. i.e.,
  737. ::
  738. b
  739. ____
  740. \ `
  741. summation(f, (i, a, b)) = ) f
  742. /___,
  743. i = a
  744. If it cannot compute the sum, it returns an unevaluated Sum object.
  745. Repeated sums can be computed by introducing additional symbols tuples::
  746. Examples
  747. ========
  748. >>> from sympy import summation, oo, symbols, log
  749. >>> i, n, m = symbols('i n m', integer=True)
  750. >>> summation(2*i - 1, (i, 1, n))
  751. n**2
  752. >>> summation(1/2**i, (i, 0, oo))
  753. 2
  754. >>> summation(1/log(n)**n, (n, 2, oo))
  755. Sum(log(n)**(-n), (n, 2, oo))
  756. >>> summation(i, (i, 0, n), (n, 0, m))
  757. m**3/6 + m**2/2 + m/3
  758. >>> from sympy.abc import x
  759. >>> from sympy import factorial
  760. >>> summation(x**n/factorial(n), (n, 0, oo))
  761. exp(x)
  762. See Also
  763. ========
  764. Sum
  765. Product, sympy.concrete.products.product
  766. """
  767. return Sum(f, *symbols, **kwargs).doit(deep=False)
  768. def telescopic_direct(L, R, n, limits):
  769. """
  770. Returns the direct summation of the terms of a telescopic sum
  771. Explanation
  772. ===========
  773. L is the term with lower index
  774. R is the term with higher index
  775. n difference between the indexes of L and R
  776. Examples
  777. ========
  778. >>> from sympy.concrete.summations import telescopic_direct
  779. >>> from sympy.abc import k, a, b
  780. >>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b))
  781. -1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a
  782. """
  783. (i, a, b) = limits
  784. s = 0
  785. for m in range(n):
  786. s += L.subs(i, a + m) + R.subs(i, b - m)
  787. return s
  788. def telescopic(L, R, limits):
  789. '''
  790. Tries to perform the summation using the telescopic property.
  791. Return None if not possible.
  792. '''
  793. (i, a, b) = limits
  794. if L.is_Add or R.is_Add:
  795. return None
  796. # We want to solve(L.subs(i, i + m) + R, m)
  797. # First we try a simple match since this does things that
  798. # solve doesn't do, e.g. solve(f(k+m)-f(k), m) fails
  799. k = Wild("k")
  800. sol = (-R).match(L.subs(i, i + k))
  801. s = None
  802. if sol and k in sol:
  803. s = sol[k]
  804. if not (s.is_Integer and L.subs(i, i + s) == -R):
  805. # sometimes match fail(f(x+2).match(-f(x+k))->{k: -2 - 2x}))
  806. s = None
  807. # But there are things that match doesn't do that solve
  808. # can do, e.g. determine that 1/(x + m) = 1/(1 - x) when m = 1
  809. if s is None:
  810. m = Dummy('m')
  811. try:
  812. sol = solve(L.subs(i, i + m) + R, m) or []
  813. except NotImplementedError:
  814. return None
  815. sol = [si for si in sol if si.is_Integer and
  816. (L.subs(i, i + si) + R).expand().is_zero]
  817. if len(sol) != 1:
  818. return None
  819. s = sol[0]
  820. if s < 0:
  821. return telescopic_direct(R, L, abs(s), (i, a, b))
  822. elif s > 0:
  823. return telescopic_direct(L, R, s, (i, a, b))
  824. def eval_sum(f, limits):
  825. (i, a, b) = limits
  826. if f.is_zero:
  827. return S.Zero
  828. if i not in f.free_symbols:
  829. return f*(b - a + 1)
  830. if a == b:
  831. return f.subs(i, a)
  832. if isinstance(f, Piecewise):
  833. if not any(i in arg.args[1].free_symbols for arg in f.args):
  834. # Piecewise conditions do not depend on the dummy summation variable,
  835. # therefore we can fold: Sum(Piecewise((e, c), ...), limits)
  836. # --> Piecewise((Sum(e, limits), c), ...)
  837. newargs = []
  838. for arg in f.args:
  839. newexpr = eval_sum(arg.expr, limits)
  840. if newexpr is None:
  841. return None
  842. newargs.append((newexpr, arg.cond))
  843. return f.func(*newargs)
  844. if f.has(KroneckerDelta):
  845. from .delta import deltasummation, _has_simple_delta
  846. f = f.replace(
  847. lambda x: isinstance(x, Sum),
  848. lambda x: x.factor()
  849. )
  850. if _has_simple_delta(f, limits[0]):
  851. return deltasummation(f, limits)
  852. dif = b - a
  853. definite = dif.is_Integer
  854. # Doing it directly may be faster if there are very few terms.
  855. if definite and (dif < 100):
  856. return eval_sum_direct(f, (i, a, b))
  857. if isinstance(f, Piecewise):
  858. return None
  859. # Try to do it symbolically. Even when the number of terms is known,
  860. # this can save time when b-a is big.
  861. # We should try to transform to partial fractions
  862. value = eval_sum_symbolic(f.expand(), (i, a, b))
  863. if value is not None:
  864. return value
  865. # Do it directly
  866. if definite:
  867. return eval_sum_direct(f, (i, a, b))
  868. def eval_sum_direct(expr, limits):
  869. """
  870. Evaluate expression directly, but perform some simple checks first
  871. to possibly result in a smaller expression and faster execution.
  872. """
  873. (i, a, b) = limits
  874. dif = b - a
  875. # Linearity
  876. if expr.is_Mul:
  877. # Try factor out everything not including i
  878. without_i, with_i = expr.as_independent(i)
  879. if without_i != 1:
  880. s = eval_sum_direct(with_i, (i, a, b))
  881. if s:
  882. r = without_i*s
  883. if r is not S.NaN:
  884. return r
  885. else:
  886. # Try term by term
  887. L, R = expr.as_two_terms()
  888. if not L.has(i):
  889. sR = eval_sum_direct(R, (i, a, b))
  890. if sR:
  891. return L*sR
  892. if not R.has(i):
  893. sL = eval_sum_direct(L, (i, a, b))
  894. if sL:
  895. return sL*R
  896. try:
  897. expr = apart(expr, i) # see if it becomes an Add
  898. except PolynomialError:
  899. pass
  900. if expr.is_Add:
  901. # Try factor out everything not including i
  902. without_i, with_i = expr.as_independent(i)
  903. if without_i != 0:
  904. s = eval_sum_direct(with_i, (i, a, b))
  905. if s:
  906. r = without_i*(dif + 1) + s
  907. if r is not S.NaN:
  908. return r
  909. else:
  910. # Try term by term
  911. L, R = expr.as_two_terms()
  912. lsum = eval_sum_direct(L, (i, a, b))
  913. rsum = eval_sum_direct(R, (i, a, b))
  914. if None not in (lsum, rsum):
  915. r = lsum + rsum
  916. if r is not S.NaN:
  917. return r
  918. return Add(*[expr.subs(i, a + j) for j in range(dif + 1)])
  919. def eval_sum_symbolic(f, limits):
  920. f_orig = f
  921. (i, a, b) = limits
  922. if not f.has(i):
  923. return f*(b - a + 1)
  924. # Linearity
  925. if f.is_Mul:
  926. # Try factor out everything not including i
  927. without_i, with_i = f.as_independent(i)
  928. if without_i != 1:
  929. s = eval_sum_symbolic(with_i, (i, a, b))
  930. if s:
  931. r = without_i*s
  932. if r is not S.NaN:
  933. return r
  934. else:
  935. # Try term by term
  936. L, R = f.as_two_terms()
  937. if not L.has(i):
  938. sR = eval_sum_symbolic(R, (i, a, b))
  939. if sR:
  940. return L*sR
  941. if not R.has(i):
  942. sL = eval_sum_symbolic(L, (i, a, b))
  943. if sL:
  944. return sL*R
  945. try:
  946. f = apart(f, i) # see if it becomes an Add
  947. except PolynomialError:
  948. pass
  949. if f.is_Add:
  950. L, R = f.as_two_terms()
  951. lrsum = telescopic(L, R, (i, a, b))
  952. if lrsum:
  953. return lrsum
  954. # Try factor out everything not including i
  955. without_i, with_i = f.as_independent(i)
  956. if without_i != 0:
  957. s = eval_sum_symbolic(with_i, (i, a, b))
  958. if s:
  959. r = without_i*(b - a + 1) + s
  960. if r is not S.NaN:
  961. return r
  962. else:
  963. # Try term by term
  964. lsum = eval_sum_symbolic(L, (i, a, b))
  965. rsum = eval_sum_symbolic(R, (i, a, b))
  966. if None not in (lsum, rsum):
  967. r = lsum + rsum
  968. if r is not S.NaN:
  969. return r
  970. # Polynomial terms with Faulhaber's formula
  971. n = Wild('n')
  972. result = f.match(i**n)
  973. if result is not None:
  974. n = result[n]
  975. if n.is_Integer:
  976. if n >= 0:
  977. if (b is S.Infinity and a is not S.NegativeInfinity) or \
  978. (a is S.NegativeInfinity and b is not S.Infinity):
  979. return S.Infinity
  980. return ((bernoulli(n + 1, b + 1) - bernoulli(n + 1, a))/(n + 1)).expand()
  981. elif a.is_Integer and a >= 1:
  982. if n == -1:
  983. return harmonic(b) - harmonic(a - 1)
  984. else:
  985. return harmonic(b, abs(n)) - harmonic(a - 1, abs(n))
  986. if not (a.has(S.Infinity, S.NegativeInfinity) or
  987. b.has(S.Infinity, S.NegativeInfinity)):
  988. # Geometric terms
  989. c1 = Wild('c1', exclude=[i])
  990. c2 = Wild('c2', exclude=[i])
  991. c3 = Wild('c3', exclude=[i])
  992. wexp = Wild('wexp')
  993. # Here we first attempt powsimp on f for easier matching with the
  994. # exponential pattern, and attempt expansion on the exponent for easier
  995. # matching with the linear pattern.
  996. e = f.powsimp().match(c1 ** wexp)
  997. if e is not None:
  998. e_exp = e.pop(wexp).expand().match(c2*i + c3)
  999. if e_exp is not None:
  1000. e.update(e_exp)
  1001. p = (c1**c3).subs(e)
  1002. q = (c1**c2).subs(e)
  1003. r = p*(q**a - q**(b + 1))/(1 - q)
  1004. l = p*(b - a + 1)
  1005. return Piecewise((l, Eq(q, S.One)), (r, True))
  1006. r = gosper_sum(f, (i, a, b))
  1007. if isinstance(r, (Mul,Add)):
  1008. non_limit = r.free_symbols - Tuple(*limits[1:]).free_symbols
  1009. den = denom(together(r))
  1010. den_sym = non_limit & den.free_symbols
  1011. args = []
  1012. for v in ordered(den_sym):
  1013. try:
  1014. s = solve(den, v)
  1015. m = Eq(v, s[0]) if s else S.false
  1016. if m != False:
  1017. args.append((Sum(f_orig.subs(*m.args), limits).doit(), m))
  1018. break
  1019. except NotImplementedError:
  1020. continue
  1021. args.append((r, True))
  1022. return Piecewise(*args)
  1023. if r not in (None, S.NaN):
  1024. return r
  1025. h = eval_sum_hyper(f_orig, (i, a, b))
  1026. if h is not None:
  1027. return h
  1028. r = eval_sum_residue(f_orig, (i, a, b))
  1029. if r is not None:
  1030. return r
  1031. factored = f_orig.factor()
  1032. if factored != f_orig:
  1033. return eval_sum_symbolic(factored, (i, a, b))
  1034. def _eval_sum_hyper(f, i, a):
  1035. """ Returns (res, cond). Sums from a to oo. """
  1036. if a != 0:
  1037. return _eval_sum_hyper(f.subs(i, i + a), i, 0)
  1038. if f.subs(i, 0) == 0:
  1039. if simplify(f.subs(i, Dummy('i', integer=True, positive=True))) == 0:
  1040. return S.Zero, True
  1041. return _eval_sum_hyper(f.subs(i, i + 1), i, 0)
  1042. hs = hypersimp(f, i)
  1043. if hs is None:
  1044. return None
  1045. if isinstance(hs, Float):
  1046. hs = nsimplify(hs)
  1047. numer, denom = fraction(factor(hs))
  1048. top, topl = numer.as_coeff_mul(i)
  1049. bot, botl = denom.as_coeff_mul(i)
  1050. ab = [top, bot]
  1051. factors = [topl, botl]
  1052. params = [[], []]
  1053. for k in range(2):
  1054. for fac in factors[k]:
  1055. mul = 1
  1056. if fac.is_Pow:
  1057. mul = fac.exp
  1058. fac = fac.base
  1059. if not mul.is_Integer:
  1060. return None
  1061. p = Poly(fac, i)
  1062. if p.degree() != 1:
  1063. return None
  1064. m, n = p.all_coeffs()
  1065. ab[k] *= m**mul
  1066. params[k] += [n/m]*mul
  1067. # Add "1" to numerator parameters, to account for implicit n! in
  1068. # hypergeometric series.
  1069. ap = params[0] + [1]
  1070. bq = params[1]
  1071. x = ab[0]/ab[1]
  1072. h = hyper(ap, bq, x)
  1073. f = combsimp(f)
  1074. return f.subs(i, 0)*hyperexpand(h), h.convergence_statement
  1075. def eval_sum_hyper(f, i_a_b):
  1076. i, a, b = i_a_b
  1077. if (b - a).is_Integer:
  1078. # We are never going to do better than doing the sum in the obvious way
  1079. return None
  1080. old_sum = Sum(f, (i, a, b))
  1081. if b != S.Infinity:
  1082. if a is S.NegativeInfinity:
  1083. res = _eval_sum_hyper(f.subs(i, -i), i, -b)
  1084. if res is not None:
  1085. return Piecewise(res, (old_sum, True))
  1086. else:
  1087. res1 = _eval_sum_hyper(f, i, a)
  1088. res2 = _eval_sum_hyper(f, i, b + 1)
  1089. if res1 is None or res2 is None:
  1090. return None
  1091. (res1, cond1), (res2, cond2) = res1, res2
  1092. cond = And(cond1, cond2)
  1093. if cond == False:
  1094. return None
  1095. return Piecewise((res1 - res2, cond), (old_sum, True))
  1096. if a is S.NegativeInfinity:
  1097. res1 = _eval_sum_hyper(f.subs(i, -i), i, 1)
  1098. res2 = _eval_sum_hyper(f, i, 0)
  1099. if res1 is None or res2 is None:
  1100. return None
  1101. res1, cond1 = res1
  1102. res2, cond2 = res2
  1103. cond = And(cond1, cond2)
  1104. if cond == False or cond.as_set() == S.EmptySet:
  1105. return None
  1106. return Piecewise((res1 + res2, cond), (old_sum, True))
  1107. # Now b == oo, a != -oo
  1108. res = _eval_sum_hyper(f, i, a)
  1109. if res is not None:
  1110. r, c = res
  1111. if c == False:
  1112. if r.is_number:
  1113. f = f.subs(i, Dummy('i', integer=True, positive=True) + a)
  1114. if f.is_positive or f.is_zero:
  1115. return S.Infinity
  1116. elif f.is_negative:
  1117. return S.NegativeInfinity
  1118. return None
  1119. return Piecewise(res, (old_sum, True))
  1120. def eval_sum_residue(f, i_a_b):
  1121. r"""Compute the infinite summation with residues
  1122. Notes
  1123. =====
  1124. If $f(n), g(n)$ are polynomials with $\deg(g(n)) - \deg(f(n)) \ge 2$,
  1125. some infinite summations can be computed by the following residue
  1126. evaluations.
  1127. .. math::
  1128. \sum_{n=-\infty, g(n) \ne 0}^{\infty} \frac{f(n)}{g(n)} =
  1129. -\pi \sum_{\alpha|g(\alpha)=0}
  1130. \text{Res}(\cot(\pi x) \frac{f(x)}{g(x)}, \alpha)
  1131. .. math::
  1132. \sum_{n=-\infty, g(n) \ne 0}^{\infty} (-1)^n \frac{f(n)}{g(n)} =
  1133. -\pi \sum_{\alpha|g(\alpha)=0}
  1134. \text{Res}(\csc(\pi x) \frac{f(x)}{g(x)}, \alpha)
  1135. Examples
  1136. ========
  1137. >>> from sympy import Sum, oo, Symbol
  1138. >>> x = Symbol('x')
  1139. Doubly infinite series of rational functions.
  1140. >>> Sum(1 / (x**2 + 1), (x, -oo, oo)).doit()
  1141. pi/tanh(pi)
  1142. Doubly infinite alternating series of rational functions.
  1143. >>> Sum((-1)**x / (x**2 + 1), (x, -oo, oo)).doit()
  1144. pi/sinh(pi)
  1145. Infinite series of even rational functions.
  1146. >>> Sum(1 / (x**2 + 1), (x, 0, oo)).doit()
  1147. 1/2 + pi/(2*tanh(pi))
  1148. Infinite series of alternating even rational functions.
  1149. >>> Sum((-1)**x / (x**2 + 1), (x, 0, oo)).doit()
  1150. pi/(2*sinh(pi)) + 1/2
  1151. This also have heuristics to transform arbitrarily shifted summand or
  1152. arbitrarily shifted summation range to the canonical problem the
  1153. formula can handle.
  1154. >>> Sum(1 / (x**2 + 2*x + 2), (x, -1, oo)).doit()
  1155. 1/2 + pi/(2*tanh(pi))
  1156. >>> Sum(1 / (x**2 + 4*x + 5), (x, -2, oo)).doit()
  1157. 1/2 + pi/(2*tanh(pi))
  1158. >>> Sum(1 / (x**2 + 1), (x, 1, oo)).doit()
  1159. -1/2 + pi/(2*tanh(pi))
  1160. >>> Sum(1 / (x**2 + 1), (x, 2, oo)).doit()
  1161. -1 + pi/(2*tanh(pi))
  1162. References
  1163. ==========
  1164. .. [#] http://www.supermath.info/InfiniteSeriesandtheResidueTheorem.pdf
  1165. .. [#] Asmar N.H., Grafakos L. (2018) Residue Theory.
  1166. In: Complex Analysis with Applications.
  1167. Undergraduate Texts in Mathematics. Springer, Cham.
  1168. https://doi.org/10.1007/978-3-319-94063-2_5
  1169. """
  1170. i, a, b = i_a_b
  1171. def is_even_function(numer, denom):
  1172. """Test if the rational function is an even function"""
  1173. numer_even = all(i % 2 == 0 for (i,) in numer.monoms())
  1174. denom_even = all(i % 2 == 0 for (i,) in denom.monoms())
  1175. numer_odd = all(i % 2 == 1 for (i,) in numer.monoms())
  1176. denom_odd = all(i % 2 == 1 for (i,) in denom.monoms())
  1177. return (numer_even and denom_even) or (numer_odd and denom_odd)
  1178. def match_rational(f, i):
  1179. numer, denom = f.as_numer_denom()
  1180. try:
  1181. (numer, denom), opt = parallel_poly_from_expr((numer, denom), i)
  1182. except (PolificationFailed, PolynomialError):
  1183. return None
  1184. return numer, denom
  1185. def get_poles(denom):
  1186. roots = denom.sqf_part().all_roots()
  1187. roots = sift(roots, lambda x: x.is_integer)
  1188. if None in roots:
  1189. return None
  1190. int_roots, nonint_roots = roots[True], roots[False]
  1191. return int_roots, nonint_roots
  1192. def get_shift(denom):
  1193. n = denom.degree(i)
  1194. a = denom.coeff_monomial(i**n)
  1195. b = denom.coeff_monomial(i**(n-1))
  1196. shift = - b / a / n
  1197. return shift
  1198. def get_residue_factor(numer, denom, alternating):
  1199. if not alternating:
  1200. residue_factor = (numer.as_expr() / denom.as_expr()) * cot(S.Pi * i)
  1201. else:
  1202. residue_factor = (numer.as_expr() / denom.as_expr()) * csc(S.Pi * i)
  1203. return residue_factor
  1204. # We don't know how to deal with symbolic constants in summand
  1205. if f.free_symbols - set([i]):
  1206. return None
  1207. if not (a.is_Integer or a in (S.Infinity, S.NegativeInfinity)):
  1208. return None
  1209. if not (b.is_Integer or b in (S.Infinity, S.NegativeInfinity)):
  1210. return None
  1211. # Quick exit heuristic for the sums which doesn't have infinite range
  1212. if a != S.NegativeInfinity and b != S.Infinity:
  1213. return None
  1214. match = match_rational(f, i)
  1215. if match:
  1216. alternating = False
  1217. numer, denom = match
  1218. else:
  1219. match = match_rational(f / S.NegativeOne**i, i)
  1220. if match:
  1221. alternating = True
  1222. numer, denom = match
  1223. else:
  1224. return None
  1225. if denom.degree(i) - numer.degree(i) < 2:
  1226. return None
  1227. if (a, b) == (S.NegativeInfinity, S.Infinity):
  1228. poles = get_poles(denom)
  1229. if poles is None:
  1230. return None
  1231. int_roots, nonint_roots = poles
  1232. if int_roots:
  1233. return None
  1234. residue_factor = get_residue_factor(numer, denom, alternating)
  1235. residues = [residue(residue_factor, i, root) for root in nonint_roots]
  1236. return -S.Pi * sum(residues)
  1237. if not (a.is_finite and b is S.Infinity):
  1238. return None
  1239. if not is_even_function(numer, denom):
  1240. # Try shifting summation and check if the summand can be made
  1241. # and even function from the origin.
  1242. # Sum(f(n), (n, a, b)) => Sum(f(n + s), (n, a - s, b - s))
  1243. shift = get_shift(denom)
  1244. if not shift.is_Integer:
  1245. return None
  1246. if shift == 0:
  1247. return None
  1248. numer = numer.shift(shift)
  1249. denom = denom.shift(shift)
  1250. if not is_even_function(numer, denom):
  1251. return None
  1252. if alternating:
  1253. f = S.NegativeOne**i * (S.NegativeOne**shift * numer.as_expr() / denom.as_expr())
  1254. else:
  1255. f = numer.as_expr() / denom.as_expr()
  1256. return eval_sum_residue(f, (i, a-shift, b-shift))
  1257. poles = get_poles(denom)
  1258. if poles is None:
  1259. return None
  1260. int_roots, nonint_roots = poles
  1261. if int_roots:
  1262. int_roots = [int(root) for root in int_roots]
  1263. int_roots_max = max(int_roots)
  1264. int_roots_min = min(int_roots)
  1265. # Integer valued poles must be next to each other
  1266. # and also symmetric from origin (Because the function is even)
  1267. if not len(int_roots) == int_roots_max - int_roots_min + 1:
  1268. return None
  1269. # Check whether the summation indices contain poles
  1270. if a <= max(int_roots):
  1271. return None
  1272. residue_factor = get_residue_factor(numer, denom, alternating)
  1273. residues = [residue(residue_factor, i, root) for root in int_roots + nonint_roots]
  1274. full_sum = -S.Pi * sum(residues)
  1275. if not int_roots:
  1276. # Compute Sum(f, (i, 0, oo)) by adding a extraneous evaluation
  1277. # at the origin.
  1278. half_sum = (full_sum + f.xreplace({i: 0})) / 2
  1279. # Add and subtract extraneous evaluations
  1280. extraneous_neg = [f.xreplace({i: i0}) for i0 in range(int(a), 0)]
  1281. extraneous_pos = [f.xreplace({i: i0}) for i0 in range(0, int(a))]
  1282. result = half_sum + sum(extraneous_neg) - sum(extraneous_pos)
  1283. return result
  1284. # Compute Sum(f, (i, min(poles) + 1, oo))
  1285. half_sum = full_sum / 2
  1286. # Subtract extraneous evaluations
  1287. extraneous = [f.xreplace({i: i0}) for i0 in range(max(int_roots) + 1, int(a))]
  1288. result = half_sum - sum(extraneous)
  1289. return result
  1290. def _eval_matrix_sum(expression):
  1291. f = expression.function
  1292. for n, limit in enumerate(expression.limits):
  1293. i, a, b = limit
  1294. dif = b - a
  1295. if dif.is_Integer:
  1296. if (dif < 0) == True:
  1297. a, b = b + 1, a - 1
  1298. f = -f
  1299. newf = eval_sum_direct(f, (i, a, b))
  1300. if newf is not None:
  1301. return newf.doit()
  1302. def _dummy_with_inherited_properties_concrete(limits):
  1303. """
  1304. Return a Dummy symbol that inherits as many assumptions as possible
  1305. from the provided symbol and limits.
  1306. If the symbol already has all True assumption shared by the limits
  1307. then return None.
  1308. """
  1309. x, a, b = limits
  1310. l = [a, b]
  1311. assumptions_to_consider = ['extended_nonnegative', 'nonnegative',
  1312. 'extended_nonpositive', 'nonpositive',
  1313. 'extended_positive', 'positive',
  1314. 'extended_negative', 'negative',
  1315. 'integer', 'rational', 'finite',
  1316. 'zero', 'real', 'extended_real']
  1317. assumptions_to_keep = {}
  1318. assumptions_to_add = {}
  1319. for assum in assumptions_to_consider:
  1320. assum_true = x._assumptions.get(assum, None)
  1321. if assum_true:
  1322. assumptions_to_keep[assum] = True
  1323. elif all(getattr(i, 'is_' + assum) for i in l):
  1324. assumptions_to_add[assum] = True
  1325. if assumptions_to_add:
  1326. assumptions_to_keep.update(assumptions_to_add)
  1327. return Dummy('d', **assumptions_to_keep)