When I was studying math I read about the series named Leibniz Series for Pi:
So I made an program for it which sums n terms of this series:
def leibniz(n):
pi = 0
for i in range(1,n+1):
if(i % 2 == 0):
pi -= 1 / (2*i - 1)
else:
pi += 1/(2*i - 1)
pi = 4 * pi
return pi
This code works but the thing is that it converges very slowly to Pi.
Edit:
I learned about the Shanks transformation and programed it
def accelrate(n,depth):
if depth == 1:
a = lebniez(n + 1)
b = lebniez(n)
c = lebniez(n-1)
return (a*c - b*b)/(a + c - 2*b)
a = accelrate(n + 1,depth - 1)
b = accelrate(n,depth - 1)
c = accelrate(n-1,depth - 1)
return (a*c - b*b)/(a + c - 2*b)
So what htis does is that it recursively applies Shanks transformation and keep on accelerating the series . But the problem now is that due to recursion it is very slow and the accuracy does not imporve if you increase the depth.
Is this the inefficiency of Shanks Transformation
So after thinking around I came up with Cache reduction in My this shanks transformation .
It does not imporves a lot but still it is a good improvement.
Here it is:
import functools as ft
@ft.lru_cache(maxsize=32)
def lebniez(n):
pi = 0
n = n + 1
for i in range(1,n):
if(i % 2 == 1):
pi -= 1 / (2*i - 1)
else:
pi += 1/(2*i - 1)
pi = abs(4 * pi)
return pi
@ft.lru_cache(maxsize=128)
def accelrate(n,depth):
if depth == 1:
a = lebniez(n + 1)
b = lebniez(n)
c = lebniez(n-1)
else:
a = accelrate(n + 1,depth - 1)
b = accelrate(n,depth - 1)
c = accelrate(n-1,depth - 1)
return (a*c - b*b)/(a + c - 2*b)
So this basic helps in make it more stable.
Next about the Inefficiency , the reason is that Shanks Transformation is just for such sequence where ratio of Error(n + 1) / Error(n) is a constant. But after applying Shanks Transformation again this can lead to inefficiency