Find The Value Of Pi
i need to find the value of pi using below pattern, pi = 4/1-4/3+4/5-4/7+4/9 i have been able to find the denominator and change the sign but i am having trouble using it in the w
Solution 1:
You just forgot to update prev
, so the loop never terminates. I also put in an abs
in case the difference is negative.
def pi(error):
prev =1current=4
i =1
while abs(current- prev) > error:
d =2.0* i +1
sign = (-1)**i
prev =currentcurrent=current+ sign *4/ d
i = i +1returncurrent
I tried pi(0.001)
with this code and got the answer 3.1420924036835256
. Note that if you try something like pi(0.000000001)
the console will freeze for a while because it will take a long time for the loop to terminate.
Solution 2:
As an alternative you could use itertools
:
itertools.count(1, 2) # generates the sequence 1, 3, 5, 7, ...
itertools.cycle([1, -1]) # generates the sequence 1, -1, 1, -1, ...
So you could do, and this generates the right values (note: moved the 4* outside of the loop to get the correct answers):
from itertools import count, cycle #, izip - if Py2defpi(error):
p = 0for sign, d inzip(cycle([1,-1]), count(1, 2)): # izip for Py2
n = sign/d
p += n
ifabs(n) < error:
breakreturn4*p
>>> pi(0.01)
3.1611986129870506>>> pi(0.0000001)
3.1415928535897395
Or using a generator:
from itertools import count, cycle, takewhile #, izip - if Py2defpi_series():
for sign, d inzip(cycle([1,-1]), count(1, 2)): # izip - if Py2yield sign/d
defpi(error):
return4*sum(takewhile(lambda x: abs(x) > error, pi_series()))
But this doesn't add the last term (need takeuntil
)
Post a Comment for "Find The Value Of Pi"