Skip to content

Instantly share code, notes, and snippets.

@komasaru
Created November 26, 2017 03:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save komasaru/d8bc42600b0ec87463b9221afd62c168 to your computer and use it in GitHub Desktop.
Save komasaru/d8bc42600b0ec87463b9221afd62c168 to your computer and use it in GitHub Desktop.
Ruby script to compute random number with Box-Muller algorithm.
#! /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