LoginSignup
3
1

More than 5 years have passed since last update.

モンテカルロ法による中学生も理解できる円周率の求め方が面白いのでPythonで

Last updated at Posted at 2018-10-29

背景

【すげえw】モンテカルロ法による中学生も理解できる円周率の求め方が面白い【物理エンジン】
↑クリックすると飛びます

算数が苦手なのでわりと感動した。

コード

だから試しに書いてみた。

pi.py
from random import random

x = 0
N = 10_000_000
for idx in range(N):
    if random()**2 + random()**2 < 1:
        x += 1
print(4*x/N) # => 3.1416836

精度について

試行回数に対してあまり精度が出ないことがわかっているらしい。
モンテカルロ法と円周率の近似計算 | 高校数学の美しい物語

その他: ライプニッツの公式を用いて算出

s = 0
for n in range(100_000):
    s += (-1) ** n / (2*n + 1)
print(s*4) # => 3.1415826535897198

その他: チャドノフスキーの公式を用いて算出

from math import factorial as fac
s = 0
for n in range(2):
    s += ( (-1)**n * fac(6*n) * (13591409+545140134*n) ) / ( fac(3*n) * (fac(n) ** 3) * (640320 ** (3*n+1.5)) )
print(1/(s*12)) # => 3.1415926535897936

もうこれわかんねぇな

3
1
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1