Skip to content

Instantly share code, notes, and snippets.

@kokudori
Created October 16, 2011 10:38
Show Gist options
  • Save kokudori/1290749 to your computer and use it in GitHub Desktop.
Save kokudori/1290749 to your computer and use it in GitHub Desktop.
モンテカルロ法で円周率計算
def monte n #点を打つ数
r = 0
n.times do
# PIの確率でHITするから円内にHITすれば+1
r+=1 if Math.sqrt(rand()**2+rand()**2) < 1
end
# 円の面積/正方形の面積がPI/4
4.0*r / n
end
t = Time.now
p monte ARGV[0] ? ARGV[0].to_i : 100
p "#{Time.now - t} sec"
# --------結果--------
$ ruby monte.rb 1
0.0
"3.4713e-05 sec"
$ ruby monte.rb 10
2.0
"5.2773e-05 sec"
$ ruby monte.rb 100
3.08
"8.8769e-05 sec"
$ ruby monte.rb 1000
3.116
"0.000727477 sec"
$ ruby monte.rb 10000
3.1336
"0.026866433 sec"
$ ruby monte.rb 100000
3.13292
"0.149040678 sec"
$ ruby monte.rb 1000000
3.142056
"1.177694786 sec"
$ ruby monte.rb 10000000
3.1424488
"11.956930154 sec"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment