線形合同法

線形合同法による疑似乱数生成器をRubyで書きました。

class LinearCongruentialRandom
  A = 1812433253

  def initialize(seed=314159)
    @state = seed
  end

  def next(max)
    @state = A * @state + 1
    @state % max.to_i.abs
  end
end

r = LinearCongruentialRandom.new
100.times do
  print "#{r.next(10000)}, "
end

実行結果です。

9228, 8685, 2306, 1419, 6008, 4025, 3326, 9479, 5188, 6565, 5946, 2339, 8768, 2305, 8166, 3999, 8748, 7245, 7986, 8459, 7128, 7385, 3406, 9719, 5908, 8725, 2426, 1779, 7088, 7265, 3046, 8639, 2668, 9005, 3266, 4299, 4648, 9945, 1086, 2759, 5028, 6085, 4506, 8019, 5808, 3425, 1526, 4079, 8988, 7965, 146, 4939, 6568, 5705, 8366, 4599, 548, 2645, 4186, 7059, 2928, 4785, 5606, 6319, 5708, 8125, 626, 6379, 888, 8665, 7246, 1239, 468, 2405, 3466, 4899, 6448, 5345, 7286, 1359, 828, 3485, 6706, 4619, 5608, 2825, 9726, 8679, 2788, 9365, 4346, 7539, 4368, 9105, 8566, 5199, 2348, 8045, 386, 5659,