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

computing pi value using python, division always zero

I am trying to use python to compute an approximation of (pi) using unlimited series.

stopping condition is for accuracy = 10**(-9)

accuracy is abs(exact_pi-computed_pi)

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

my code:

from math import sqrt

exact_pi=3.14159265358979323846
accuracy=10**(-9)
computed_pi=float(sqrt(12))
k=1

while abs(float(computed_pi)-float(exact_pi))>accuracy:
   
    num1=float((-3)**(-k))
    num2=float((2*k+1))
    computed_pi=float(computed_pi)+ float(num1/num2)
    k=k+1

The result of float(num1/num2) after some iterations for k=100 for example it outputs 0 so it gets into an infinite loop. can someone help?

PI FORMULA

>Solution :

As @quamrana noticed you have missed sum operation.

# your code before while

while abs(computed_pi - exact_pi) > accuracy:
    multiplier = sum((-3)**(-i)/(2 * i + 1) for i in range(k))
    computed_pi = 12**0.5 * multiplier
    k += 1

or slightly optimized version (thanks again to quamrana)

multipler = 0
while abs(computed_pi - exact_pi) > accuracy:
    multiplier += (-3)**(-k) / (2 * k + 1)
    computed_pi = 12**0.5 * multiplier
    k += 1
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