Last active
December 14, 2015 00:59
-
-
Save komasaru/5003302 to your computer and use it in GitHub Desktop.
Ruby script to calc uniform random numbers by chi-squared distribution method.
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
# -*- coding: utf-8 -*- | |
class Chi2Rndnum | |
# 各種定数定義 | |
A = 1103515245 # 乗数 | |
C = 12345 # 加数 | |
M = 2 ** 31 # 法 | |
N = 1000 # 発生させる乱数の個数 | |
M_MAX = 10 # 整数乱数の範囲 | |
F = N / M_MAX.to_f # 期待値 | |
S = 40.0 / F # ヒストグラム用スケール | |
# 計算クラス | |
class Calc | |
# コンストラクタ | |
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 | |
# 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 | |
# 結果表示 | |
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 | |
end | |
# メイン処理 | |
begin | |
# 計算クラスインスタンス化 | |
obj_calc = Calc.new | |
# 一様乱数生成 | |
obj_calc.generate_rndnum | |
# 結果表示 | |
obj_calc.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