[1-1] 乱数を発生するモジュールをインポートします。
In [1]:
from numpy.random import random
[1-2] 「釘」を投げるシュミレーションで円の面積を計算します。
釘の個数を変えながら、計算を繰り返します。
In [2]:
for num in [100, 1000, 10000, 100000, 1000000]:
xs = -1+random(num)*2
ys = -1+random(num)*2
inside = 0
for x, y in zip(xs, ys):
if x*x + y*y <= 1:
inside += 1
area = 4.0 * inside / num
print "n=%7d, area=%f" % (num, area)