I came across an interesting Python exercise and tried to code it. I need to write a code that does the following (without the help of any libs or modules):
- Create the infinite series
1 - 1/3 + 1/5 - 1/7 + ...
- Perform the calculation:
4*(1 - 1/3 + 1/5 - 1/7 + ...)
- Perform N iterations until the absolute value of the difference between iteration n and n-1 is less than or equal to 0.00000000005, then return the calculated value.
My code goes as following:
def pi(n):
a = [0]*n
calc = [0]*n
dif = 1
while abs(dif) > 0.00000000005:
for k in range(0,n):
if k==0:
a[k] = -((-1)**(k+1))*(1/(2*k+1))
calc[k] = 4*sum(a)
else:
a[k] = -((-1)**(k+1))*(1/(2*k+1))
calc[k] = 4*sum(a)
dif = calc[k] - calc[k-1]
return calc[k]
I probably have to call the function with n being a really big number, as I don't know when the difference will be <= 0.00000000005. Is there a way to perform it without setting a range or should I always start with a huge value for n? I still couldn't get any results so I don't know if my n isn't high enough and I'll get no result at all or if it's just a problem with memory.
while, you don't need another one withfor.nepochs? If yes, you can remove theforblock.npartial sums, only the previous and the current one.