La serie
import math
def a(n): return 1/n**2
PASSI = 20
S_n = 0
for n in range(1,PASSI+1):
a_n = a(n)
S_n += a_n
pi_n = math.sqrt(6*S_n)
print("%02i | %12.10f | %12.10f | %12.10f" %(n, a_n, S_n, pi_n))
Output
01 | 1.0000000000 | 1.0000000000 | 2.4494897428
02 | 0.2500000000 | 1.2500000000 | 2.7386127875
03 | 0.1111111111 | 1.3611111111 | 2.8577380332
04 | 0.0625000000 | 1.4236111111 | 2.9226129861
05 | 0.0400000000 | 1.4636111111 | 2.9633877010
06 | 0.0277777778 | 1.4913888889 | 2.9913764947
07 | 0.0204081633 | 1.5117970522 | 3.0117739478
08 | 0.0156250000 | 1.5274220522 | 3.0272978567
09 | 0.0123456790 | 1.5397677312 | 3.0395075896
10 | 0.0100000000 | 1.5497677312 | 3.0493616360
11 | 0.0082644628 | 1.5580321940 | 3.0574815067
12 | 0.0069444444 | 1.5649766384 | 3.0642878178
13 | 0.0059171598 | 1.5708937982 | 3.0700753719
14 | 0.0051020408 | 1.5759958390 | 3.0750569156
15 | 0.0044444444 | 1.5804402834 | 3.0793898260
16 | 0.0039062500 | 1.5843465334 | 3.0831930203
17 | 0.0034602076 | 1.5878067411 | 3.0865580258
18 | 0.0030864198 | 1.5908931608 | 3.0895564350
19 | 0.0027700831 | 1.5936632439 | 3.0922450523
20 | 0.0025000000 | 1.5961632439 | 3.0946695241

import math # sqrt
import matplotlib.pyplot as plt # ...
def a(n): return 1/n**2
PASSI = 10
N = []
A = []
PI = []
S_n = 0
for n in range(1, PASSI+1):
a_n = a(n)
S_n += a_n
pi_n = math.sqrt(6*S_n)
print(n, a_n, S_n, pi_n)
N.append(n)
A.append(a_n)
PI.append(pi_n)
plt.subplot(2, 1, 1)
plt.grid()
plt.plot(N, PI, linewidth="2")
plt.title("Pi greco: serie di Eulero")
plt.ylim(0,3.5)
plt.ylabel("pi(n)")
plt.subplot(2, 1, 2)
plt.bar(N, A, color="green")
plt.grid()
plt.xlabel("n")
plt.ylabel("a(n)")
plt.show()
fractions
Utilizzando il modulo fractions si ottengono le approssimazioni successive come frazioni!
import fractions
import math
def a(n): return fractions.Fraction(1, n**2)
PASSI = 20
S_n = 0
for n in range(1, PASSI+1):
a_n = a(n)
S_n += a_n
pi_n = math.sqrt(6*S_n)
print("%02i | %5s | %35s | %12.10f" %(n, a_n, S_n, pi_n))
Output
01 | 1 | 1 | 2.4494897428
02 | 1/4 | 5/4 | 2.7386127875
03 | 1/9 | 49/36 | 2.8577380332
04 | 1/16 | 205/144 | 2.9226129861
05 | 1/25 | 5269/3600 | 2.9633877010
06 | 1/36 | 5369/3600 | 2.9913764947
07 | 1/49 | 266681/176400 | 3.0117739478
08 | 1/64 | 1077749/705600 | 3.0272978567
09 | 1/81 | 9778141/6350400 | 3.0395075896
10 | 1/100 | 1968329/1270080 | 3.0493616360
11 | 1/121 | 239437889/153679680 | 3.0574815067
12 | 1/144 | 240505109/153679680 | 3.0642878178
13 | 1/169 | 40799043101/25971865920 | 3.0700753719
14 | 1/196 | 40931552621/25971865920 | 3.0750569156
15 | 1/225 | 205234915681/129859329600 | 3.0793898260
16 | 1/256 | 822968714749/519437318400 | 3.0831930203
17 | 1/289 | 238357395880861/150117385017600 | 3.0865580258
18 | 1/324 | 238820721143261/150117385017600 | 3.0895564350
19 | 1/361 | 86364397717734821/54192375991353600 | 3.0922450523
20 | 1/400 | 17299975731542641/10838475198270720 | 3.0946695241