Home > Software design >  Limit and summation in Python
Limit and summation in Python

Time:04-14

I am trying currently to calculate the limit of the following formula:

enter image description here

I tried the following code:

nsum(lambda k: ((x)**(2k))/fac(2k), [0, inf])

where x = np.pi/2 it returned the following message:

 File "C:\Users\AppData\Local\Temp/ipykernel_14/335.py", line 3
    nsum(lambda k: ((-1)**2*(x)**(2k))/fac(2k), [0, inf])
                                   ^
SyntaxError: invalid syntax

I tired this too:

sym.limit((np.pi/2)**(2k))/fac(2k), k, sym.oo)

I got the same error:

File "C:\Users\AppData\Local\Temp/ipykernel_14/40.py", line 1
    sym.limit(((np.pi/2)**(2k))/fac(2k), k, sym.oo)
                                    ^
SyntaxError: invalid syntax

I could not figure out where my problem lies, any idea would be appreciated.

CodePudding user response:

With Python, multiplication needs to be written explicitly. In your case, you need to write 2*k.

Edit: it is clear that this is your first time with Python and the distinction between numerical and symbolic libraries. Here, I'm going to discuss SymPy and the way I would approach your problem:

from sympy import var, Sum, pi, factorial, limit
# create symbols n and k
var("k, n")
# create a symbolic expression.
# NOTE: I have replace the upper limit n with infinity
expr1 = Sum((pi / 2)**(2 * k) / factorial(2 * k), (k, 0, oo))
expr1.doit()
# output: cosh(pi/2)

# If you wanted to compute the limit of the original expression:
expr2 = Sum((pi / 2)**(2 * k) / factorial(2 * k), (k, 0, n))
limit(expr2, n, oo)
# It throws an error!
  • Related