I need help with my code. I want to write a code that can calculate the error of "math.pi and pi using Gregory series". The range of error is 1.0E-1~1.0E-8
. Here is my code:
import math
EPSILON=0.1
def ans(terms):
result=0.0
for n in range(terms):
result+=(-1.0)**n/(2.0*n+1.0)
return 4*result
if abs(pi-ans)<=EPSILON:
print n,ans,abs(pi-ans)
else:
print("out of different")
I can get the ans, like ans(60) >>> 3.1249271439289967
, but I can't get the output of print n,ans,abs(pi-ans)
, what's wrong with my code?
It's because your print statements are indented and it makes them part of your ans()
function.
Your code has several other errors
pi
but should use math.pi
ans
in your print statement without using argumentYour code should look like this :
import math
EPSILON=0.1
def ans(terms):
result=0.0
for n in range(terms):
result+=(-1.0)**n/(2.0*n+1.0)
return 4*result
n = 60
res = ans(n)
if abs(math.pi-res) <= EPSILON:
print n,res,abs(math.pi-res)
else:
print("out of different")