Search code examples
rubyrandomruby-1.9mersenne-twister

Distributed sequential random number generation in Ruby 1.9.2


The Random class in Ruby 1.9.2 is guaranteed to generate random numbers in the same order, given a particular seed and range. For instance:

r = Random.new(23)
r.rand(100)         # 83
r.rand(100)         # 40

But suppose I want to generate the next number in the sequence on another computer (without re-generating the earlier numbers in the sequence). This should be possible, given the previous output. Is there a way to do this with the Random class? Or do I have to write my own implementation of the Mersenne twister?

[Edit: As pointed out in the comments below, it is not in fact possible to determine the state of a Random instance just from the output, because only part of the state (specifically, the low 32 bits) are used for the output.]


Solution

  • Can't test, but the generator can be marshalled, according to Marc-André Lafortune here. So this might work:

    r = Random.new(23)
    r.rand(100)         # 83
    r.rand(100)         # 40
    
    File.open("/path/to/file","w") do |f|
      Marshal.dump(r,f)
    end
    
    # later, may be on another computer
    
    File.open("/path/to/file","r") do |f|
      @v = Marshal.load(f)
    end
    
    puts @v.rand(100)