ガウス・ルジャンドル法によるπの算出です。
rubyで書かれたサンプルプログラムをpythonに移植しました。
mpmathの計算桁数を1000にしてます。
πの近似値を一桁ずつ延々と無限ループで出力しますが、精度は、100000桁までチェックしました。
pi.py
#!/usr/bin/python3
import mpmath
import sys
k, a, b, a1, b1 = 2, 4, 1, 12, 4
mpmath.mp.dps=1000
f=0
while(True):
# Next approximation
p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d = a / b
d1 = a1 / b1
while(d == d1):
print (int(d),end='')
sys.stdout.flush()
if f==0:
print(".",end='')
f=1
a, a1 = 10*(a%b), 10*(a1%b1)
d, d1 = a/b, a1/b1
ruby で書かれたパッケージプログラム
#!/usr/bin/ruby
k, a, b, a1, b1 = 2, 4, 1, 12, 4
while 1
# Next approximation
p, q, k = k*k, 2*k+1, k+1
a, b, a1, b1 = a1, b1, p*a+q*a1, p*b+q*b1
# Print common digits
d = a / b
d1 = a1 / b1
while d == d1
print d
$stdout.flush
a, a1 = 10*(a%b), 10*(a1%b1)
d, d1 = a/b, a1/b1
end
end
rubyとは日本人が作ったコンピュータ言語であり、宝石であり、日本語で紅玉と言います。紅玉とは宝石ルビーの和名であり、林檎の一種であり、林檎の紅玉は、英語でJonathanと言います。