import matplotlib.pyplot as plt from matplotlib import interactive from numpy import pi,log10 interactive(True) N = int(input("N terms = ")) # prepare plot frame and description plt.figure(figsize=(6,5)) plt.xlabel('log$_{10}$ N',fontsize=14) plt.ylabel('log$_{10}$ |$x-\pi$|',fontsize=14) plt.title('Accelerated convergence of Leibniz ser. for $\pi$',fontsize=14) plt.axis([0.,log10(N*4), -16.,0.]) plt.grid(True,color=(.8,.9,.97)) ''' Series x = 4/1 -4/3 +4/5 -4/7 +...+(+-1)/(odd N) due to Leibniz is accelerated by repeated averaging of neighboring terms. This is done with almost zero storage and one series summation ''' x = x_1 = a = b = c = const = 4. i = 1 while(i < N): # c is the number of people/obj. i += 2 const = -const a_1 = a b_1 = b c_1 = c x_2 = x_1 x_1 = x x = x + const/i a = (x+x_1)*0.5 b = (a+a_1)*0.5 c = (b+b_1)*0.5 d = (c+c_1)*0.5 if(i<700 or (i>200 and (i-1)%8==0)): i0 = log10(i) y0 = log10(max(abs(x-pi),1e-20)) e1 = log10(max(abs(a-pi),1e-20)) e2 = log10(max(abs(b-pi),1e-20)) e3 = log10(max(abs(c-pi),1e-20)) e4 = log10(max(abs(d-pi),1e-20)) # plot singe point plt.scatter(i0,y0,s=5,color=(.3,0.,.8),linewidth=2) plt.scatter(i0,e1,s=5,color=(.7,1.,.2),linewidth=2) plt.scatter(i0,e2,s=4,color=(0.,1.,0.),linewidth=2) plt.scatter(i0,e3,s=4,color=(.2,.4,1.),linewidth=2) plt.scatter(i0,e4,s=5,color=(.9,.3,.0),linewidth=2) plt.text(i0+.1,y0,"Leibniz") plt.text(i0+.1,e1,"1av") plt.text(i0+.1,e2,"2av") plt.text(i0+.1,e3,"3av") plt.text(i0+.1,-15.3,"4av") ans = input("ok?")