Home > Mobile >  computing pi value using python, division always zero
computing pi value using python, division always zero

Time:10-27

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)

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

CodePudding user response:

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

CodePudding user response:

There are a number of things wrong with your code:

  1. You are initializing computed_pi to be sqrt(12) rather than 0
  2. You are starting your sum at k=1 rather than k=0
  3. You aren't accumulating the terms
  4. You are wasting cpu cycles (and sacrificing readability) constant;y converting floats to floats.

Fixing these leads to:

from math import sqrt

exact_pi=3.14159265358979323846
accuracy=10**(-9)
computed_pi=0
factor = sqrt(12)
k=0

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

Output:

3.1415926541725754
  • Related