Last active
December 9, 2017 09:24
-
-
Save junpeitsuji/23f70256ad1cf85e1ec70e88d7eff94c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
# Box=Muller 法に基づいて, 平均 0.0 分散 1.0 の正規乱数を発生させる | |
def box_muller | |
x = Random.rand(1.0) | |
y = Random.rand(1.0) | |
z = Math.sqrt(-2.0 * Math.log(x)) * Math.cos(2.0*Math::PI*y) | |
w = Math.sqrt(-2.0 * Math.log(x)) * Math.sin(2.0*Math::PI*y) # not use | |
return z | |
end | |
# テスト | |
def __test_box_muller | |
div = 21 # ヒストグラムの区間数 | |
data = Array.new(div, 0) | |
display_num = 500 # ヒストグラムに表示する点数 | |
data_num = 100000 # 発生させる乱数の総数 | |
# 乱数を発生させてヒストグラムを保管する配列に入れる | |
data_num.times do | |
# Box=Muller法を実行 | |
z = box_muller | |
# 3sigma 以内のデータを data に格納 | |
sigma = 3.0 | |
u = (z * ((div-1)*0.5/sigma) + div*0.5).to_i | |
if u >= 0 && u < div | |
data[u] += 1 | |
end | |
end | |
# ヒストグラム表示 | |
data.each do |x| | |
puts ("*" * (x/(data_num/display_num))) | |
end | |
end | |
# テストを実行 | |
if $0 == __FILE__ then | |
__test_box_muller | |
end | |
# 結果 | |
=begin | |
$ ruby box_muller.rb | |
* | |
* | |
*** | |
******* | |
*********** | |
****************** | |
***************************** | |
**************************************** | |
************************************************** | |
********************************************************* | |
********************************************************** | |
********************************************************* | |
************************************************* | |
*************************************** | |
***************************** | |
******************* | |
*********** | |
****** | |
*** | |
* | |
=end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment