[PYTHON] I tried to find 100 million digits of pi

how?

\zeta(2) = \sum_{n=1}^{\infty}\frac{1}{n^2} = \frac{\pi^2}{6}

([Basel Problem](https://en.wikipedia.org/wiki/%E3%83%90%E3%83%BC%E3%82%BC%E3%83%AB%E5%95%8F%E9 % A1% 8C)))

This formula can be used to find an approximation of $ \ pi $. 1 Find $ \ sum_ {n = 1} ^ {a} \ frac {1} {n ^ 2} $ with an integer of $ 1 $ or more from 1 as $ a $ 2. $ \ times6 $ the answer obtained in 1. 3. Calculate the square root of the answer obtained in 2. This value is an approximation of $ \ pi $.

So I implemented it with python. The code is omitted.


So it takes a few hours to calculate ... There is no sign that it will end at all ... It seems that it takes about 18 hours when calculating the time. And it's not very accurate ... Moreover, it seems to be a (?) Expression that is difficult to converge, so I will try another expression.


** Gauss-Legendre algorithm **

a_0 = 1\quad
b_0 = \frac{1}{\sqrt{2}}\quad
t_0 = \frac{1}{4}\quad
p_0 = 1\\
\\
a_{n+1} = \frac{a_n+b_n}{2}\\
b_{n+1} = \sqrt(a_nb_n)\\
t_{n+1} = t_n - 2(a_n - a_{n+1})^2\\
p_{n+1} = 2p_n
\\
\\
\pi \approx \frac{(a+b)^2}{4t}

(Quoted from Wikipedia)


py.py


#I'm sorry it's not in place.
from decimal import *
import math
import sys,time

d = time.time()
# set
keta = int(sys.argv[1])
c = (int(sys.argv[2]))
getcontext().prec = keta+11
print("init")
a = 1
print("b",time.time()-d)
b = 1/(Decimal(2).sqrt())
print("t",time.time()-d)
t = Decimal(0.25)
print("p",time.time()-d)
p = 1
print("n",time.time()-d)
n = math.ceil(math.log2(keta))
print("n =",n,"time =",time.time()-d)
d = time.time()
# pi
for i in range(n):
        an1 = (a+b)/2
        bn1 = Decimal(a*b).sqrt()
        tn1 = t - p * (a-an1) * (a-an1)
        pn1 = p*2
        a = an1
        b = bn1
        t = tn1
        p = pn1
        if p % c == 0:
                print(i,"\t",float((a + b) * (a + b) / (4*t)),"\ttime:", time.time()-d)

pi =  (a+ b) * (a + b) / (Decimal(4)*t)
print(float(pi))
with open("pi.txt","w") as f:
        f.write(str(pi)[:2+keta])

$python filename 100000000 1#1 can be any multiplier of 2
(Various are displayed)
$ head -c 10 pi.txt
3.14159265

Besides this https://www.blog.umentu.work/google-circle-3-14/ You can also use the algorithms on this site.

Recommended Posts