Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Limit and summation in Python

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

enter image description here

I tried the following code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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!
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading