random number with seed

后端 未结 6 1218
暗喜
暗喜 2021-01-05 15:35

Reference: link text

i cannot understand the following line , can anybody provide me some example for the below statement?

If two instances of Random are cre

6条回答
  •  温柔的废话
    2021-01-05 16:08

    With the same seed value, separate instances of Random will return/generate the same sequence of random numbers; more on this here: http://www.particle.kth.se/~lindsey/JavaCourse/Book/Part1/Tech/Chapter04/javaRandNums.html

    Ruby Example:

    class LCG; def initialize(seed=Time.now.to_i, a=2416, b=374441, m=1771075); @x, @a, @b, @m = seed % m, a, b, m; end; def next(); @x = (@a * @x + @b) % @m; end; end
    
    irb(main):004:0> time = Time.now.to_i
    => 1282908389
    
    irb(main):005:0> r = LCG.new(time)
    => #
    irb(main):006:0> r.next
    => 45940
    irb(main):007:0> r.next
    => 1558831
    irb(main):008:0> r.next
    => 1204687
    irb(main):009:0> f = LCG.new(time)
    => #
    irb(main):010:0> f.next
    => 45940
    irb(main):011:0> f.next
    => 1558831
    irb(main):012:0> f.next
    => 1204687
    

    Based on the values a/b/m, the result will be the same for a given seed. This can be used to generate the same "random" number in two places and both sides can depend on getting the same result. This can be useful for encryption; although obviously, this algorithm isn't cryptographically secure.

提交回复
热议问题