Last active
April 19, 2018 04:33
-
-
Save komasaru/774f3259b71881b6c36678360db4ec36 to your computer and use it in GitHub Desktop.
Ruby script to test for uniformity of random number with Chi-square 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 Chi2Rndnum | |
A = 1103515245 # 乗数 | |
C = 12345 # 加数 | |
M = 2 ** 31 # 法 | |
N = 1000 # 発生させる乱数の個数 | |
M_MAX = 10 # 整数乱数の範囲 | |
F = N / M_MAX.to_f # 期待値 | |
S = 40.0 / F # ヒストグラム用スケール | |
def initialize | |
# 乱数の種の初期値 | |
@r = 12345 | |
# 件数格納用配列初期化 | |
@hist = Array.new(M_MAX + 1, 0) | |
# カイ2乗検定初期値 | |
@e = 0.0 | |
end | |
# 一様乱数生成 | |
def generate_rndnum | |
1.upto(N) do |i| | |
rank = rnd | |
@hist[rank] += 1 | |
end | |
end | |
# 結果表示 | |
def display | |
1.upto(M_MAX) do |i| | |
# 件数表示 | |
printf("%3d:%3d ", i, @hist[i]) | |
# ヒストグラム表示 | |
0.upto(@hist[i] * S - 1) { |j| print "*" } | |
puts | |
# カイ2乗検定 | |
@e = @e + (@hist[i] - F) * (@hist[i] - F) / F | |
end | |
# カイ2乗検定値表示 | |
puts "χ2 = #{@e}" | |
end | |
private | |
# 1 ~ 10 の整数乱数 | |
def rnd | |
# 0 ~ 2の31乗 未満の整数乱数 | |
@r = (A * @r + C) % M | |
# 0 ~ 1 未満の実数乱数に 10 を乗じて 1 を加えることで | |
# 1 ~ 10 の整数乱数にする | |
return M_MAX * (@r / (M - 0.9)) + 1; | |
end | |
end | |
if __FILE__ == $0 | |
begin | |
obj = Chi2Rndnum.new | |
obj.generate_rndnum | |
obj.display | |
rescue => e | |
puts "[例外発生] #{e}" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment