K iVddlmZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z dd lmZdd lmZdd lmZmZdd lmZdd lmZmZddlmZddlmZddlmZddl m!Z!m"Z"m#Z#m$Z$ddl%m&Z&ddl'm(Z(m)Z)ddl*m+Z+ddl,m-Z-m.Z.ddl/m0Z0ddl1m2Z2m3Z3ddl4m5Z5ddl6m7Z7ddl8m9Z9ddl:m;Z;ddlZ>ddl?m@Z@ddlAmBZBmCZCddlDmEZEmFZFmGZGdd lHmIZIdd!lJmKZKdd"lLmMZMdd#lNmOZOdd$lPmQZQdd%lRmSZSmTZTdd&lUmVZVdd'lWZWGd(d)e eZXd*ZYd+ZZd,Z[d-Z\d.Z]d/Z^d0Z_d1Z`d2Zad3Zbd4Zcy')5) annotations) is_decreasing)AccumulationBounds)ExprWithIntLimits) AddWithLimits) gosper_sum)Expr)Add)Tuple) Derivativeexpand)Mul)Float_illegal)Eq)S)ordered)DummyWildSymbolsymbols) factorial) bernoulliharmonic)re)explog) Piecewise)cotcsc)hyper)KroneckerDelta)zeta)Integral)AndNot)apart)PolynomialErrorPolificationFailed)parallel_poly_from_exprPolyfactor)together) limit_seq)O)residue)Contains) FiniteSetInterval)siftNceZdZUdZdZded<dZdZdZdZ d Z d Z d Z d Z d ZdZdZdZdZddZdZdZy)SumaI Represents unevaluated summation. Explanation =========== ``Sum`` represents a finite or infinite series, with the first argument being the general form of terms in the series, and the second argument being ``(dummy_variable, start, end)``, with ``dummy_variable`` taking all integer values from ``start`` through ``end``. In accordance with long-standing mathematical convention, the end term is included in the summation. Finite sums =========== For finite sums (and sums with symbolic limits assumed to be finite) we follow the summation convention described by Karr [1], especially definition 3 of section 1.4. The sum: .. math:: \sum_{m \leq i < n} f(i) has *the obvious meaning* for `m < n`, namely: .. math:: \sum_{m \leq i < n} f(i) = f(m) + f(m+1) + \ldots + f(n-2) + f(n-1) with the upper limit value `f(n)` excluded. The sum over an empty set is zero if and only if `m = n`: .. math:: \sum_{m \leq i < n} f(i) = 0 \quad \mathrm{for} \quad m = n Finally, for all other sums over empty sets we assume the following definition: .. math:: \sum_{m \leq i < n} f(i) = - \sum_{n \leq i < m} f(i) \quad \mathrm{for} \quad m > n It is important to note that Karr defines all sums with the upper limit being exclusive. This is in contrast to the usual mathematical notation, but does not affect the summation convention. Indeed we have: .. math:: \sum_{m \leq i < n} f(i) = \sum_{i = m}^{n - 1} f(i) where the difference in notation is intentional to emphasize the meaning, with limits typeset on the top being inclusive. Examples ======== >>> from sympy.abc import i, k, m, n, x >>> from sympy import Sum, factorial, oo, IndexedBase, Function >>> Sum(k, (k, 1, m)) Sum(k, (k, 1, m)) >>> Sum(k, (k, 1, m)).doit() m**2/2 + m/2 >>> Sum(k**2, (k, 1, m)) Sum(k**2, (k, 1, m)) >>> Sum(k**2, (k, 1, m)).doit() m**3/3 + m**2/2 + m/6 >>> Sum(x**k, (k, 0, oo)) Sum(x**k, (k, 0, oo)) >>> Sum(x**k, (k, 0, oo)).doit() Piecewise((1/(1 - x), Abs(x) < 1), (Sum(x**k, (k, 0, oo)), True)) >>> Sum(x**k/factorial(k), (k, 0, oo)).doit() exp(x) Here are examples to do summation with symbolic indices. You can use either Function of IndexedBase classes: >>> f = Function('f') >>> Sum(f(n), (n, 0, 3)).doit() f(0) + f(1) + f(2) + f(3) >>> Sum(f(n), (n, 0, oo)).doit() Sum(f(n), (n, 0, oo)) >>> f = IndexedBase('f') >>> Sum(f[n]**2, (n, 0, 3)).doit() f[0]**2 + f[1]**2 + f[2]**2 + f[3]**2 An example showing that the symbolic result of a summation is still valid for seemingly nonsensical values of the limits. Then the Karr convention allows us to give a perfectly valid interpretation to those sums by interchanging the limits according to the above rules: >>> S = Sum(i, (i, 1, n)).doit() >>> S n**2/2 + n/2 >>> S.subs(n, -4) 6 >>> Sum(i, (i, 1, -4)).doit() 6 >>> Sum(-i, (i, -3, 0)).doit() 6 An explicit example of the Karr summation convention: >>> S1 = Sum(i**2, (i, m, m+n-1)).doit() >>> S1 m**2*n + m*n**2 - m*n + n**3/3 - n**2/2 + n/6 >>> S2 = Sum(i**2, (i, m+n, m-1)).doit() >>> S2 -m**2*n - m*n**2 + m*n - n**3/3 + n**2/2 - n/6 >>> S1 + S2 0 >>> S3 = Sum(i, (i, m, m-1)).doit() >>> S3 0 See Also ======== summation Product, sympy.concrete.products.product References ========== .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM, Volume 28 Issue 2, April 1981, Pages 305-350 https://dl.acm.org/doi/10.1145/322248.322255 .. [2] https://en.wikipedia.org/wiki/Summation#Capital-sigma_notation .. [3] https://en.wikipedia.org/wiki/Empty_sum z tuple[tuple[Symbol, Expr, Expr]]limitsctj||g|i|}t|ds|Std|jDr t d|S)Nr9c3DK|]}t|dk7xsd|vyw)N)len).0ls _/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/sympy/concrete/summations.py zSum.__new__..s$&>%&G==,, ,'H !rJcf|jr%|jdur|jjSyyrV)rWrXrG is_negativerOs r@_eval_is_negativezSum._eval_is_negativer[rJcL|jr|jjryyyrL)rWrG is_finiterOs r@_eval_is_finitezSum._eval_is_finites"  ! !dmm&=&='> !rJc |jddr|jjdi|}n |j}i}|jD]}t |}|s|||d<|r|j Dcic]\}}|| }}}|j |jdi|} t| tr*t| D cgc]} | j |c} } | S| | j |} | S|} | S|jjr0|j} || k7r| jSt|St|jD]\} } | \} }}||z }|dk(rtjcS|jr|j r |dz|dz }}| }t#|| ||f}|P||jk(r|j%|| ||f}||cS|cS|j&|g|j| dcS|}|jddr"t|t(s|jdi|S|Scc}}wcc} w)NdeepTrrr8)getrGdoitr9)_dummy_with_inherited_properties_concreteitemsxreplace isinstancetuple is_Matrixr_eval_matrix_sum enumeraterZero is_integerr]eval_sumeval_zeta_functionfuncr)rPhintsfrepsxabdkvundodidiexpandednlimitabdifnewf zeta_functions r@rfzSum.doitsN 99VT "" ""+U+A A;; !C9#>A SV  ! %)ZZ\2TQAqD2D2*$--%**3U3C#u%s;!QZZ-;< J ll4(JJ == " "{{}Hx}}&#D) )!$++. HAuGAq!a%Cbyvv ~~#//1ua!e1BA1ay)D| %$($;$;A1ay$IM$0,,K$499Q9QR99A' * 99VT "a+qvv&[3 1` and `q > 0` NwexcludeyzrT) is_comparablerrrOneInfinityrmatchrr$r&r'r2 Naturals0r) rPrur9r}rrrrrresultcoeffsqs r@rrzSum.eval_zeta_functions31a ??q1q5**1q!aee)QY.GH H AJJ  sQC($sQC*@$sUVTWBXa1WWa!eaiaR01 16 1q VAY..Eq Aq F1I%)Aed1aj0!#hr1;;&?"@"Q%!%%-PR"D\+ + 2rJcvt|tr||jvrtjS|j t |j}}|jd}|r|j|g|}|\}}}||jvs||jvryt||d}|j||} | S)a Differentiate wrt x as long as x is not in the free symbols of any of the upper or lower limits. Explanation =========== Sum(a*b*x, (x, 1, a)) can be differentiated wrt x or b but not `a` since the value of the sum is discontinuous in `a`. In a case involving a limit variable, the unevaluated derivative is returned. rdNT)evaluate) rjr free_symbolsrrorGlistr9poprsr ) rPxrur9r_rrdfrvs r@_eval_derivativezSum._eval_derivative's" a Qd.?.?%?66MMM4 #46 2  !%f%A1a  !q~~"5 1t , YYr5 ! rJc|jd\}}}|j|||z}t|jdk(r|jd}n|j|jdd}t |||dz|fj S)Nrdrr)argssubsr=rsr7rf)rPrstepryrupper new_upperrus r@_eval_difference_deltazSum._eval_difference_deltaJsiim 1eJJq!d(+ tyy>Q  ! A 499Sb>*A1q%!)Y/05577rJc `|j}|jddr|jdi|}tjt |}g}g}|D]}|j trtjt |}g}|D]E} t| tr"|j| jdi|5|j| G|jt||j|ddl m } m} t| |g|} | | |jS)NrcTr) factor_sum sum_combine)r9r8)rGresimplifyr make_argsrhasr7rrjappend_eval_simplifysympy.simplify.simplifyrrr9) rPkwargsrGtermss_to_ttermsubterms out_termssubtermrrrs r@rzSum._eval_simplifyUs== ::fd #(x((262H fX./ !Dxx}==6 '2G!'3/!(()?)?)?)I&)IJ"((12 3 ?+ 4 ' !, D[%,,&55rJc R)*+,-tdt\}}}|jdd,|jdd*|jdd-|jj }t |j dkDr td*jr-jrtjS*tjur-tjurXt|,dtjfjxr+t|,tjdfjSddlm}||j!,, i}- *tj-t#,j$dd }|j!,|i}|,t'*-)|j(rt|j*D]U\}}|dk(s+|j-j.tjus6t|,*-f} | jcStjS t1|,} | | j2d urtj4S t1t7|,} | | j2d urtj4St9|,tjf} | j:j=,|z} | 0| |d krtjS| |d k\rtj4S| j:j=d,|zt?d,z |zzt?t?d,z  |zzz xsP| j:j=d,|zt?d,z  |zzt?t?d,z  |zzz }|c||dkDs;||dk(r||dkDs+||||cxk(rdk(r*ntj4S||dkDrtjStj4S t1,|z,}|!|j@r|dkDrtj4S|j!,,dzi}dd l!m"}ddl#m$}||||z } t1|,}|Z|j@rN|tjJur>> from sympy import factorial, S, Sum, Symbol, oo >>> n = Symbol('n', integer=True) >>> Sum(n/(n - 1), (n, 4, 7)).is_convergent() True >>> Sum(n/(2*n + 1), (n, 1, oo)).is_convergent() False >>> Sum(factorial(n)/5**n, (n, 1, oo)).is_convergent() False >>> Sum(1/n**(S(6)/5), (n, 1, oo)).is_convergent() True See Also ======== Sum.is_absolutely_convergent sympy.concrete.products.Product.is_convergent zp q r)rFrrrzNconvergence checking for more than one symbol containing series is not handledrTintegerpositiveNFrdcombsimp)powsimp)solvesetm)rc tt|jfj}||jrt j Syy#t$rYywxYwN)r/r7infrfr`rtrueNotImplementedError)g_ning_valintervalrsyms r@_dirichlet_testz*Sum.is_convergent.._dirichlet_testxsb'C#x||Q1G(H(M(M(OQRSG*w/@/@ vv 0A**sAA A A c  t|}|o|js3t|trR|j|j z jr.t |fjrtjSyyyy#t$rYywxYwr) r/r`rjrmaxminr7is_absolutely_convergentrrr)g1_ng2_nlim_val lower_limitr upper_limits r@_bounded_convergent_testz3Sum.is_convergent.._bounded_convergent_tests'c2G*0A0A"7,>?$[[7;;6AA"4#{K)HIbbd'(vv  eB@+ +sA9B B  B zFThe algorithm to find the Sum convergence of %s is not yet implemented)8rrr9rGrr=rrr`rrNegativeInfinityrr7 is_convergentrrirnamer4 is_Piecewiseras_setsupr/rMfalseabsr0exprrr is_numbersympy.simplify.combsimprsympy.simplify.powsimprNaNr gammasimp NegativeOnerrsympy.solvers.solvesetrdiffrjr3r%rfis_Mulsetrange itertools combinationsr).rPprr sequence_termrsym_rscondrr lim_val_absorder p_series_test n_log_testlim_compnext_sequence_termrrratio lim_ratiotest_val lim_evaluateddict_valcheck_intervalrmaxima integral_valintegral_val_evaluatedrargsetrrra_tupleb_seta_nb_ndirichbc_test_symrrrrrs. @@@@@r@rzSum.is_convergent|sT't,1akk!nQkk!nQ' kk!nQ'  ..0 })) *Q .%'IJ J  [%:%:66M !,, ,ajj(=31::*>?MMOYMC1C1CQ+GHVVXY 8$]%;%;S3$K%HIM&,K**KSXXtd;%..T{; K5  % %+00 - d4<4;;=#4#4 #BD3 ["ABA??,,  - 66M  s3G"w%'?ww #C $6+>%+Gww-#qzz!23 ((a0  $Q"$vv Q2%wwjj&&q#q&QsUQ*>sC#J;?OQR?R*R'STXjj&&q#q&3qu:+1A*A#s1S5zkBRTUBU*U'VW   !1 !A!# 1 (9A*Q-41477N:DA9J66M77N  ]!2C8H#(:(:x!|ww +33S#'NC42!3M!ABC !%-I$)<)<RSRWRWAWy>A%77Ny>A%66M >M&++Cq9:<=>?H))+H #Hc2&7+<+<{ vv { ww  %c-&81S5&A3GM(]-D-D 1$66M 1$77N !&&q}}sQw'?'AB{s# hqk8(L66M3-,,S13A%N  *vzz/C/C%fjj(,,?N  & =. 9 =.. 9'!Ck#B D -9->->-@*-77 !7!A!ABB82 ::  ::??DYFc4(A  1c&k* '(55dA> 'G"S\1Ew-Cu+C$S(3!0!5!-#)M6sC@G*& ' '{{1~a %..T{; !#;>K#MN NU#   #   <#   # I '  #   2+s+^7 4_41_A _'$_'6._9%_9;=` 9` 0`7 __ __ _$#_$' _65_69 `` `` `&%`&cptt|j|jj S)ax Checks for the absolute convergence of an infinite series. Same as checking convergence of absolute value of sequence_term of an infinite series. References ========== .. [1] https://en.wikipedia.org/wiki/Absolute_convergence Examples ======== >>> from sympy import Sum, Symbol, oo >>> n = Symbol('n', integer=True) >>> Sum((-1)**n, (n, 1, oo)).is_absolutely_convergent() False >>> Sum((-1)**n/n**2, (n, 1, oo)).is_absolutely_convergent() True See Also ======== Sum.is_convergent )r7rrGr9rrOs r@rzSum.is_absolutely_convergents'63t}}%t{{3AACCrJc ft|}t|}|j}t|jdk7r t d|jd\kDdk(r6z dk(r t j t j fSdzdz c| }t j }|rJjrjrt|z dz}|r|jr3tt|Dcgc]}|j|zc}}n|j}|rFt|jd|k} | dk(r |t|fS| dk(s|t j fS|}td|D]M}|j|z}t|jd|kr|dk7r|t|fcS||z }Oz dz|k(r|t j fS|z td} t!|j| | f} |r| j#} || z }fd} | |\} }| |zd z }|j%}td|d zD]}| |\}}t'd |zt)d |zz ||z z}||kDrnt|rW|rU|jd}|t j*ur"t j*t j*fcSt||krn||z }|j%d d }||ztfScc}w) a Return an Euler-Maclaurin approximation of self, where m is the number of leading terms to sum directly and n is the number of terms in the tail. With m = n = 0, this is simply the corresponding integral plus a first-order endpoint correction. Returns (s, e) where s is the Euler-Maclaurin approximation and e is the estimated error (taken to be the magnitude of the first omitted term in the tail): >>> from sympy.abc import k, a, b >>> from sympy import Sum >>> Sum(1/k, (k, 2, 5)).doit().evalf() 1.28333333333333 >>> s, e = Sum(1/k, (k, 2, 5)).euler_maclaurin() >>> s -log(2) + 7/20 + log(5) >>> from sympy import sstr >>> print(sstr((s.evalf(), e.evalf()), full_prec=True)) (1.26629073187415, 0.0175000000000000) The endpoints may be symbolic: >>> s, e = Sum(1/k, (k, a, b)).euler_maclaurin() >>> s -log(a) + log(b) + 1/(2*b) + 1/(2*a) >>> e Abs(1/(12*b**2) - 1/(12*a**2)) If the function is a polynomial of degree at most 2n+1, the Euler-Maclaurin formula becomes exact (and e = 0 is returned): >>> Sum(k, (k, 2, b)).euler_maclaurin() (b**2/2 + b/2 - 1, 0) >>> Sum(k, (k, 2, b)).doit() b**2/2 + b/2 - 1 With a nonzero eps specified, the summation is ended as soon as the remainder term is less than the epsilon. rzMore than 1 limitrTr<Frctjur|jdfS|j|jfS)Nr)rrr)rrrr}s r@fpointz#Sum.euler_maclaurin..fpointsBAJJyyA))99Q?DIIaO3 3rJrr)intrGr=r9rErro is_Integerr is_polynomialr rrrevalfrr%rfrrrr)rPrreps eval_integralrurryrtestrIr fafbitermggagb term_evalfrrr}s @@@r@euler_maclaurinzSum.euler_maclaurinsV F F MM t{{ q 01 1++a.1a Ed?1uzvvqvv~%q5!a%DAqA FF || 1q519%!//!,E!H=q!&&AE*=>vva|tzz!}-3Dt| #d)|+"em#QVV|+q!A66!QU+D4::a=)C/DAI #d)|+IA  1uqyA~!&&y FA #J QVVAq\Aq!9 - A Q 4Bb!  FF1Iq!a% -AAYFBQqS>)AaC.0"r':D1ut!ZZ] &55!%%<'z?S( IAq!e,A -5y#d)##[>s<L.cXt|}t|D]*\}}t|tr|j |||<,d}g}t|j D]3\}}|}||vr| }|d|ddz|ddz f}|j |5t||jzg|S)a] Reverse the order of a limit in a Sum. Explanation =========== ``reverse_order(self, *indices)`` reverses some limits in the expression ``self`` which can be either a ``Sum`` or a ``Product``. The selectors in the argument ``indices`` specify some indices whose limits get reversed. These selectors are either variable names or numerical indices counted starting from the inner-most limit tuple. Examples ======== >>> from sympy import Sum >>> from sympy.abc import x, y, a, b, c, d >>> Sum(x, (x, 0, 3)).reverse_order(x) Sum(-x, (x, 4, -1)) >>> Sum(x*y, (x, 1, 5), (y, 0, 6)).reverse_order(x, y) Sum(x*y, (x, 6, 0), (y, 7, -1)) >>> Sum(x, (x, a, b)).reverse_order(x) Sum(-x, (x, b + 1, a - 1)) >>> Sum(x, (x, a, b)).reverse_order(0) Sum(-x, (x, b + 1, a - 1)) While one should prefer variable names when specifying which limits to reverse, the index counting notation comes in handy in case there are several symbols with the same name. >>> S = Sum(x**2, (x, a, b), (x, c, d)) >>> S Sum(x**2, (x, a, b), (x, c, d)) >>> S0 = S.reverse_order(0) >>> S0 Sum(-x**2, (x, b + 1, a - 1), (x, c, d)) >>> S1 = S0.reverse_order(1) >>> S1 Sum(x**2, (x, b + 1, a - 1), (x, d + 1, c - 1)) Of course we can mix both notations: >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(x, 1) Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) >>> Sum(x*y, (x, a, b), (y, 2, 5)).reverse_order(y, x) Sum(x*y, (x, b + 1, a - 1), (y, 6, 1)) See Also ======== sympy.concrete.expr_with_intlimits.ExprWithIntLimits.index, reorder_limit, sympy.concrete.expr_with_intlimits.ExprWithIntLimits.reorder References ========== .. [1] Michael Karr, "Summation in Finite Terms", Journal of the ACM, Volume 28 Issue 2, April 1981, Pages 305-350 https://dl.acm.org/doi/10.1145/322248.322255 rrr) rrnrjr indexr9rr7rG) rPindices l_indicesr}indxer9rr?s r@ reverse_orderzSum.reverse_order(s|M  + 0GAtdC(#zz$/ !  0 !$++. HAuAI~B1XuQx!|U1X\: MM!   1t}}$.v..rJcddlm}|jjr/t |t |jg|j Sy)Nr)Product)sympy.concrete.productsr$rGrSrrr9)rPrrr$s r@_eval_rewrite_as_ProductzSum._eval_rewrite_as_Productws93 == ) )ws4==1@DKK@A A *rJN)rrrT)__name__ __module__ __qualname____doc__ __slots____annotations__rBrQrTrZr^rarfrrrrrrrrr"r&r8rJr@r7r7*srBHI ,,. --;z+*!F 8%6NbNH D:h$VM/^BrJr7c@t|g|i|jdS)a Compute the summation of f with respect to symbols. Explanation =========== The notation for symbols is similar to the notation used in Integral. summation(f, (i, a, b)) computes the sum of f with respect to i from a to b, i.e., :: b ____ \ ` summation(f, (i, a, b)) = ) f /___, i = a If it cannot compute the sum, it returns an unevaluated Sum object. Repeated sums can be computed by introducing additional symbols tuples:: Examples ======== >>> from sympy import summation, oo, symbols, log >>> i, n, m = symbols('i n m', integer=True) >>> summation(2*i - 1, (i, 1, n)) n**2 >>> summation(1/2**i, (i, 0, oo)) 2 >>> summation(1/log(n)**n, (n, 2, oo)) Sum(log(n)**(-n), (n, 2, oo)) >>> summation(i, (i, 0, n), (n, 0, m)) m**3/6 + m**2/2 + m/3 >>> from sympy.abc import x >>> from sympy import factorial >>> summation(x**n/factorial(n), (n, 0, oo)) exp(x) See Also ======== Sum Product, sympy.concrete.products.product F)rc)r7rf)rurrs r@ summationr.}s(d q %7 %f % * * * 66rJc |\}}}tt|Dcgc]-}|j|||z|j|||z z/c}Scc}w)a Returns the direct summation of the terms of a telescopic sum Explanation =========== L is the term with lower index R is the term with higher index n difference between the indexes of L and R Examples ======== >>> from sympy.concrete.summations import telescopic_direct >>> from sympy.abc import k, a, b >>> telescopic_direct(1/k, -1/(k+2), 2, (k, a, b)) -1/(b + 2) - 1/(b + 1) + 1/(a + 1) + 1/a )r rr)LRrr9r}rrrs r@telescopic_directr2sO(IQ1 eAhG1q5!AFF1a!e$44G HHGs2Ac|\}}}|js |jrytd}| j|j|||z}d}|r2||vr.||}|jr|j|||z|zdk(sd}|t d} ddlm} | |j||| z|z| xsg}|D cgc]A} | js|j||| z|zjjr| C}} t|dk7ry|d}|dkrt||t||||fS|dkDrt||||||fSy#t$rYywxYwcc} w)zi Tries to perform the summation using the telescopic property. Return None if not possible. Nryrrsolver)is_Addrrrr rsympy.solvers.solversr5rrrMr=r2r) r0r1r9r}rrrysolrrr5sis r@ telescopicr:s IQ1xx188 S A 2**QVVAq1u% &C A qCx F 1q5!1A!5!:A  y #J  3q!a%(1,a06BC 9b2==q!b&!A%--/7799 s8q= F1u As1v1ay99 Q Aq1a)44 #  9s)EE"4E" EEc |\ }}|jrtjS |jvr |||z dzzS||k(r|j |S|j rB|j r6||kDr1t | |tjz|tjz fSt|trwt fd|jDsYg}|jD]9}t |j|}|y|j||jf;|j|S|j!t"r1ddlm}m}|j+dd}|||dr |||S||z } | j,} | r| dkrt/| ||fSt|tryt1|j3 ||f} | | S| rt/| ||fSy)Nrc3TK|]}|jdjv!yw)rN)rr)r>argr}s r@rAzeval_sum..s$CS1 000Cs%()deltasummation_has_simple_deltac"t|tSr)rjr7rs r@zeval_sum..s jC(rJc"|jSr)r-rAs r@rBzeval_sum..s ahhjrJrd)rMrrorrrrqrrjrrDrrrrrsrr#deltar>r?replacer eval_sum_directeval_sum_symbolicr) rur9rrnewargsr=newexprr>r?rdefinitevaluer}s @r@rqrqsIQ1yyvv !a%!)}Avvva|1??q1uAq155y!aee)455!YCAFFCCGvv 4"388V4?23  4 1667# #uu^< II (   Qq *!!V, , a%C~~HS3Yq1a),,!Y ahhj1a) 4E  q1a),,rJc n|\}}}||z }|jr|j|\}}|dk7r*t||||f}|rz||z} | tjurc| S|j \} } | j |st| |||f} | r| | zS| j |st| |||f} | r| | zS t||}|jr|j|\}}|dk7r0t||||f}|ro||dzz|z} | tjurR| S|j \} } t| |||f}t| |||f}d||fvr||z} | tjur| Stt|dzDcgc]}|j|||zc}S#t$rYwxYwcc}w)z Evaluate expression directly, but perform some simple checks first to possibly result in a smaller expression and faster execution. rrN) ras_independentrGrr as_two_termsrr(r)r6r rr)rr9r}rrr without_iwith_irrr0r1sRsLlsumrsumjs r@rGrG)s IQ1 a%C {{ //2 6 >Aq 2AaKAEE>H$$&DAq558$QAq 2R4K558$QAq 2a4K  T1~ {{ //2 6 >Aq 2AsQw'!+AEE>H$$&DAq"1q!Qi0D"1q!Qi0DD$<'4KAEE>H eC!Gn=1a!e$= >>/    .>s= F#F2# F/.F/c |}|\}}}|j|s |||z dzzS|jr|j|\}}|dk7r*t||||f}|rz||z} | tj urc| S|j \} } | j|st| |||f} | r| | zS| j|st| |||f} | r| | zS t||}|jr|j \} } t| | |||f}|r|S|j|\}}|dk7r3t||||f}|r_|||z dzz|z} | tj ur?| St| |||f}t| |||f}d||fvr||z} | tj ur| Std}|j||z}|||}|jr|dk\r|tjur|tjus$|tjur"|tjurtjSt!|dz|dzt!|dz|z |dzz j#S|jrR|dk\rM|dk(rt%|t%|dz z St%|t'|t%|dz t'|z S|jtjtjsj|jtjtjs;td|g}td|g}td|g}td }|j)j||z}||j+|j#j||z|z}||j-|||zj/|}||zj/|}|||z||dzzz zd|z z } |||z dzz}t1|t3|tj4f| d fSt7||||f} t9| t:t<frdd lm }dd l!m"}| jFtI|ddjFz }|tK| }||jFz} g}!tM| D]u}" |||"}|rt3|"|dntjN}#|#d k7rB|!jQtS|j.|#jT|jW|#fn|!jQ| d ft1|!S| dtj fvr| St[||||f}$|$|$St]||||f} | | S|j_}%|%|k7rt|%|||fSy#t$rYwxYw#tX$rYwxYw)Nrrrrdc1rc2c3wexpT)denomr4F)0rrrNrHrrrOr(r)r6r:rrr rrrrrrrrupdaterrrrr rjrr sympy.simplify.radsimpr\r7r5rr r.rrrr7rrfreval_sum_hypereval_sum_residuer-)&rur9f_origr}rrrPrQrrr0r1rRrSlrsumrTrUrrrXrYrZr[r!e_exprrr?r\r5 non_limitdenden_symrrzrhfactoreds& r@rHrHis FIQ1 558!a%!)} xx,,Q/ 6 >!&1a)4AaKAEE>H>>#DAq558&q1a)4R4K558&q1a)4a4K  !QK xx~~11a!Q+ L,,Q/ 6 >!&1a)4Aq1uqy)A-AEE>H%QAq 2D$QAq 2DD$<'4KAEE>H S A WWQT]F  1I <<AvO1C1C(C+++0C::%"1q5!a%09QUA3FFQOWWYY!q&7#A;!a%88#As1v.!a%Q1HHH EE!**a00 1 EE!**a00 1 $ $ $ $ $ $F| IIK  bDj ) =EE$K&&(..r!tby9E VMM!$VMM!$q!ta!a%j()1q51q1uqyM !R155\!2QI>> q1a) $ a#c # 4 3qr );)H)HHI $C#"2"22GDW% c1 A'(1ad aggAEz Saff)=v%F%K%K%Mq$QR   KKD "d# # T155M !Hv1ay)A}!Q+A}}}H6 Aq!955S    n+s% V&6A1V6& V32V36 WWc B|dk7r t|j|||z|dS|j|ddk(r_ddlm}||j|t ddddk(rt j dfSt|j||dz|dSddlm}|||}|yt|trdd lm }||}dd l m }dd l m}dd lm} | t#|\} } | j%|\} } | j%|\}}| |g}| |g}ggg}t'd D]}||D]}d}|j(r'|j*}|j,}|j.syt1||}|j3dk7ry|j5\}}||xx||zzcc<||xx||z g|zz cc<|ddgz}|d}|d|dz }t7|||}||}|j|d||z|j8fS)z) Returns (res, cond). Sums from a to oo. rrr}Trr) hypersimpN) nsimplifyr) hyperexpand)fractionr)_eval_sum_hyperrrrrrrorjrjrrkrrsympy.simplify.hyperexpandrlr^rmr- as_coeff_mulris_Powrbaser r,degree all_coeffsr"convergence_statement)rur}rrrjhsrkrrlrmnumerr\toptoplbotbotlabfactorsparamsryfacmulrrrapbqrrgs r@rnrnsAvqvvaQ/A66vva|q4 AFF1eCEF G1 L664< qvvaQ/A661 1aB z"e5 r]06/F2J'LE5""1%IC""1%IC sBTlG"XF 1X #1: #CCzzgghh~~S! AxxzQ<<>DAq qEQVOE 1I!A#s "I # #" aSB B 1be A b"aA A 66!Q< A &(?(? ??rJc\|\}}}|j|dury||z jryt||||f}|tjk7r|tj ur/t |j|| || }|t||dfSd}||}t |||} | || |kDryt |||dz} | || |kDry| | c\} } \} } t| | } | dk(ryt| | z | f|dfS|tj urt |j|| |d} t ||d} | | y| \} } | \} } t| | } | dk(s!| jtjk(ryt| | z| f|dfSt |||}||\}}|dk(rr|jre|j|tddd|z}|js |jrtjS|j rtj Syt||dfSy)NFTc4tfdtDS)Nc3@K|]}j|ywr)count)r>rrs r@rAz3eval_sum_hyper....Bs%CQaggaj%Cs)sumrrAs`r@rBz eval_sum_hyper..Bs#%C(%C"CrJrrr}r)is_hypergeometricr r7rrrrnrrr&rEmptySetrrrYrMr])rui_a_br}rrold_sumres n_illegalhadres1res2cond1cond2rrcs r@r_r_0sJGAq!1& A!aAYGAJJ "" "!!&&QB-QB7C wo66CIA,C"1a+D|y4"1aQ/D|y4+/ (MT5=D%ue$Du}dTk407D/B BA  qvva!}a3q!Q' <4< e e5%  5=DKKMQZZ7$+t,wo>> !Q "C 1 :{{FF1eCEIJ==AII::%]]---wo..rJc |\}}|jrB|jr6||kDr1t||tjz|tjz fSd}d}d}fd}t dfd}|j hz ry|j s#|tjtjfvsy|j s#|tjtjfvsy|tjk7r|tjk7ry||} | rd} | \} } n(||tjzz } | rd } | \} } ny| j| jz d kry||ftjtjfk(rT|| } | y| \}}|ry|| | | }|Dcgc]}t||}}tj t|zS|jr|tjusy|| | s|| }|j sy|d k(ry| j|} | j|} || | sy| rJtjztj|z| j!z| j!z z}n!| j!| j!z }t|||z ||z fS|| } | y| \}}|rR|Dcgc] }t#|}}t%|}t'|}t)|||z d zk(sy|t%|kry|| | | }||zDcgc]}t||}}tj t|z}|s||j+d izd z }t-t#|d Dcgc]}|j+|i}}t-d t#|Dcgc]}|j+|i}}|t|zt|z }|S|d z }t-t%|d zt#|Dcgc]}|j+|i}}|t|z }|Scc}wcc}wcc}wcc}wcc}wcc}w) aCompute the infinite summation with residues Notes ===== If $f(n), g(n)$ are polynomials with $\deg(g(n)) - \deg(f(n)) \ge 2$, some infinite summations can be computed by the following residue evaluations. .. math:: \sum_{n=-\infty, g(n) \ne 0}^{\infty} \frac{f(n)}{g(n)} = -\pi \sum_{\alpha|g(\alpha)=0} \text{Res}(\cot(\pi x) \frac{f(x)}{g(x)}, \alpha) .. math:: \sum_{n=-\infty, g(n) \ne 0}^{\infty} (-1)^n \frac{f(n)}{g(n)} = -\pi \sum_{\alpha|g(\alpha)=0} \text{Res}(\csc(\pi x) \frac{f(x)}{g(x)}, \alpha) Examples ======== >>> from sympy import Sum, oo, Symbol >>> x = Symbol('x') Doubly infinite series of rational functions. >>> Sum(1 / (x**2 + 1), (x, -oo, oo)).doit() pi/tanh(pi) Doubly infinite alternating series of rational functions. >>> Sum((-1)**x / (x**2 + 1), (x, -oo, oo)).doit() pi/sinh(pi) Infinite series of even rational functions. >>> Sum(1 / (x**2 + 1), (x, 0, oo)).doit() 1/2 + pi/(2*tanh(pi)) Infinite series of alternating even rational functions. >>> Sum((-1)**x / (x**2 + 1), (x, 0, oo)).doit() pi/(2*sinh(pi)) + 1/2 This also have heuristics to transform arbitrarily shifted summand or arbitrarily shifted summation range to the canonical problem the formula can handle. >>> Sum(1 / (x**2 + 2*x + 2), (x, -1, oo)).doit() 1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 4*x + 5), (x, -2, oo)).doit() 1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 1), (x, 1, oo)).doit() -1/2 + pi/(2*tanh(pi)) >>> Sum(1 / (x**2 + 1), (x, 2, oo)).doit() -1 + pi/(2*tanh(pi)) References ========== .. [#] http://www.supermath.info/InfiniteSeriesandtheResidueTheorem.pdf .. [#] Asmar N.H., Grafakos L. (2018) Residue Theory. In: Complex Analysis with Applications. Undergraduate Texts in Mathematics. Springer, Cham. https://doi.org/10.1007/978-3-319-94063-2_5 ctd|jD}td|jD}td|jD}td|jD}|xr|xs|xr|S)z1Test if the rational function is an even functionc30K|]\}|dzdk(ywrrNr8r>r}s r@rAz=eval_sum_residue..is_even_function..?Q!?c30K|]\}|dzdk(ywrr8rs r@rAz=eval_sum_residue..is_even_function..rrc30K|]\}|dzdk(ywrrNr8rs r@rAz=eval_sum_residue..is_even_function..>tA >rc30K|]\}|dzdk(ywrr8rs r@rAz=eval_sum_residue..is_even_function..rr)allmonoms)rwr\ numer_even denom_even numer_odd denom_odds r@is_even_functionz*eval_sum_residue..is_even_functionso? ?? ? ?? >u||~>> >u||~>> )zGy/FYGrJc|j\}} t||f|\\}}}||fS#ttf$rYywxYwr)as_numer_denomr+r*r))rur}rwr\opts r@match_rationalz(eval_sum_residue..match_rationalsW'') u "95%.!"L NUECe|#O4  s -??c~|jj}t|d}d|vry|d|d}}||fS)Nc|jSr)rprAs r@rBz5eval_sum_residue..get_poles..s allrJTF)sqf_part all_rootsr5)r\roots int_roots nonint_rootss r@ get_polesz#eval_sum_residue..get_polessJ **,U23 5="'+uU|< ,&&rJc|j}|j|z}|j|dz z}| |z |z }|S)Nr)rscoeff_monomial)r\rrrshiftr}s r@ get_shiftz#eval_sum_residue..get_shiftsP LLO  A &  QqS *a!  rJrc|j|jz j}|s!|ttjzz}|S|t tjzz}|Sr)as_exprrr rPir!)rwr\ alternatingresidue_factorr}rs r@get_residue_factorz,eval_sum_residue..get_residue_factorse--/EMMO;AA!QG c!$$(m +N c!$$(m +NrJNFTrrr)rr`rrrrr rrrrsr1rrr`rrr rrr=rir)rurrrrrrrrrrrwr\polesrrrrootresiduesr int_roots_max int_roots_minfull_sumhalf_sumi0extraneous_negextraneous_posr extraneousr}rs @@r@r`r`lsZJGAq! 1??q1uAq155y!aee)#<==H' c A ~~ LLA!**a.@.@!AA LLA!**a.@.@!AA A  1 ? 1a E   uq1==!#33Q7 K LE5 ||Aa(1, 1v!$$ajj11%  ="' < +E5+FAMNGNAt4NNus8}$$ KKAO E5 )%  A: E" E"u-  q AMM5$85==?$JU]]_$\]A %--/1AAqw%#899 e E }#I|+454SY5 5I I 9~!>!BB I 'ukBN=F=UVT40VHVus8}$H qzz1a&11Q69>c!fa8HI"!**aW-II8=aQ8HI"!**aW-IIC//#n2EE !|H16c)nq6H#a&0QR"!**aW%RJR J 'F MMOF6WJISs$4Q1.Q6 Q;2R%RR c|j}|jD]R}|\}}}||z }|js|dkdk(r |dz|dz }}| }t||||f}|B|j cSy)NrTr)rGr9r rGrf) expressionrurr}rrrrs r@rmrmPsA"" #1a!e >>aD 1ua!e1B"1q!Qi0Dyy{" #rJc |\}}}||g}gd}i}i}|D]@ |jj d}|rd| <'t fd|Dsr}assums r@rAz<_dummy_with_inherited_properties_concrete..ws6qEEM*6s)rx) _assumptionsrerr]r) r9rrrr?assumptions_to_considerassumptions_to_keepassumptions_to_add assum_truers @r@rgrg_sGAq! AA@(-^^''t4 )-  & 6A6 6(, u % - ""#560/00rJ)d __future__rsympy.calculus.singularitiesr!sympy.calculus.accumulationboundsrexpr_with_intlimitsrexpr_with_limitsrgosperr sympy.core.exprr sympy.core.addr sympy.core.containersr sympy.core.functionr rsympy.core.mulrsympy.core.numbersrrsympy.core.relationalrsympy.core.singletonrsympy.core.sortingrsympy.core.symbolrrrr(sympy.functions.combinatorial.factorialsr%sympy.functions.combinatorial.numbersrr$sympy.functions.elementary.complexesr&sympy.functions.elementary.exponentialrr$sympy.functions.elementary.piecewiser(sympy.functions.elementary.trigonometricr r!sympy.functions.special.hyperr"(sympy.functions.special.tensor_functionsr#&sympy.functions.special.zeta_functionsr$sympy.integrals.integralsr%sympy.logic.boolalgr&r'sympy.polys.partfracr(sympy.polys.polyerrorsr)r*sympy.polys.polytoolsr+r,r-sympy.polys.rationaltoolsr.sympy.series.limitseqr/sympy.series.orderr0sympy.series.residuesr1sympy.sets.containsr2sympy.sets.setsr3r4sympy.utilities.iterablesr5rr7r.r2r:rqrGrHrnr_r`rmrgr8rJr@rs"6@2+ '2.$"&::>E3;:=/C7.(&FGG.+ )(/*P B-*P Bf27jI0+5\.-b=?@N6b3@l9/xaH #1rJ