Skip to content

Instantly share code, notes, and snippets.

@ramalho
Last active August 1, 2021 01:27
Show Gist options
  • Save ramalho/727a10eab410e5fc994436e53bdfb108 to your computer and use it in GitHub Desktop.
Save ramalho/727a10eab410e5fc994436e53bdfb108 to your computer and use it in GitHub Desktop.
Checking if an infinite series converges on π
$ python3 pi_series.py
1 3.000000000000000000000000000000 -0.14159265358979312
2 3.122498999199199154475081741111 -0.01909365439059396
3 3.138470965295042880427445197711 -0.0031216882947502356
4 3.141030313220715797228876908775 -0.0005623403690773188
5 3.141485090117183798241740078083 -0.00010756347260931776
6 3.141571214690141999881234369241 -2.1438899651116117e-05
7 3.141588250040259211459670041222 -4.403549533904538e-06
8 3.141591728079553114127975277370 -9.2551024000187e-07
9 3.141592455512121073724074449274 -1.980776720422739e-07
10 3.141592610570093757615950380568 -4.301969935838201e-08
11 3.141592644132424894110044988338 -9.457368221887918e-09
12 3.141592651489385268348542012973 -2.1004078476494215e-09
13 3.141592653119234412883997720201 -4.705587031139657e-10
14 3.141592653483579411499704292510 -1.0621370449825918e-10
15 3.141592653565661308334711065982 -2.4131807663252403e-11
16 3.141592653584278860279255241039 -5.5142557187082275e-12
17 3.141592653588526573571471089963 -1.2665424264923786e-12
18 3.141592653589500905297882127343 -2.922107000813412e-13
19 3.141592653589725614438066259027 -6.750155989720952e-14
20 3.141592653589777128786408866290 -1.5987211554602254e-14
21 3.141592653589789563284284668043 -3.552713678800501e-15
22 3.141592653589792227819543768419 -8.881784197001252e-16
23 3.141592653589792671908753618482 -4.440892098500626e-16
# checking if this series is legit:
# https://twitter.com/infseriesbot/status/1421630403132022787
from math import factorial, sqrt, pi
def series():
n, s = 1, 0.0
while True:
m = factorial(n - 1)
s += (m * m) / factorial(2 * n)
yield s
n += 1
def display():
prev = 0
for step, s in enumerate(series(), 1):
p = sqrt(18 * s)
if p == prev: # maximum precision
break
print(f'{step:2} {p:1.30f} {p - pi}')
prev = p
display()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment