Ruby script to compute random number with Box-Muller algorithm.
This file contains 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
#! /usr/local/bin/ruby | |
#********************************************* | |
# ボックス=ミューラー法法による正規乱数生成 | |
#********************************************* | |
class RndnumBoxMuller | |
M = 10 # 平均 | |
S = 2.5 # 標準偏差 | |
N = 10000 # 発生させる乱数の個数 | |
PI = 3.1415926535 # 円周率 | |
SCALE = N / 100.0 # ヒストグラム用スケール | |
def initialize | |
@hist = Array.new( M * 5, 0 ) | |
end | |
def generate_rndnum | |
0.upto( N - 1 ) do |i| | |
res = rnd | |
@hist[res[0]] += 1 | |
@hist[res[1]] += 1 | |
end | |
end | |
def display | |
0.upto( M * 2 ) do |i| | |
printf("%3d:%4d | ", i, @hist[i]) | |
1.upto( @hist[i] / SCALE ) { |j| print "*" } | |
puts | |
end | |
end | |
private | |
def rnd | |
r_1 = rand | |
r_2 = rand | |
x = S * Math.sqrt(-2 * Math.log(r_1)) * Math.cos(2 * PI * r_2) + M | |
y = S * Math.sqrt(-2 * Math.log(r_1)) * Math.sin(2 * PI * r_2) + M | |
return [ x.to_i, y.to_i ] | |
end | |
end | |
begin | |
obj = RndnumBoxMuller.new | |
obj.generate_rndnum | |
obj.display | |
rescue => e | |
$stderr.puts "[例外発生] #{e}" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment