以下のアルゴリズムを参考にして、ループと四則演算だけで円周率を計算してみました
import time
import math
def calculate_pi(r):
t, total = 0, 0
y = r
# 中心座標(0,0) 半径rの円を描く
for x in range(r):
t += x
if t > y:
t -= y
y -= 1
total += y
# 45°まで
if x >= y:
return (total * 2 - x * y) * 4 / (r*r)
# 半径の値
radius_values = [1000, 10000, 100000, 1000000, 10000000, 100000000]
# 見出し
print("半径 タイム(秒) π ")
# 結果を表形式で表示
for r in radius_values:
start_time = time.time()
pi = calculate_pi(r)
end_time = time.time()
print("%-12d %-12.4f" % (r, end_time - start_time), pi)
print("math.pi: %.16f" % (math.pi))
実行結果
半径 タイム(秒) π
1000 0.0000 3.15022
10000 0.0030 3.14246948
100000 0.0480 3.1416806076
1000000 0.3399 3.141601450108
10000000 1.8053 3.1415935333564
100000000 17.9820 3.1415927415701512
math.pi: 3.1415926535897931
コードの解説は、以下の記事を参照ください
2024.01.27 追記
同じ環境でjuliaでも試してみた
using Printf
function calculate_pi(r)
t, total = 0, 0
y = r
for x in 0:r
if t > y - x
t -= y - x
y -= 1
else
t += x
end
total += y
if x >= y
return (total * 2 - x^2) * 4 / r^2
end
end
end
# 半径の値
radius_values = [10000, 100000, 1000000, 10000000, 100000000, 1000000000]
# 見出し
println("半径 タイム(秒) π ")
# 結果を表形式で表示
for r in radius_values
start_time = time()
pi = calculate_pi(r)
end_time = time()
@printf("%-12d %-12.4f ", r, end_time - start_time)
println(pi)
end
println("π: ", π*1.0)
半径 タイム(秒) π
10000 0.0240 3.14246948
100000 0.0000 3.1416806076
1000000 0.0020 3.141601450108
10000000 0.0210 3.1415935333564
100000000 0.2010 3.1415927415701512
1000000000 1.8970 3.141592665216587
π: 3.141592653589793
julia 速い