10

I was trying to be clever about deterministically picking random stuff, and found this:

irb(main):011:0> Random.new(Random.new(1).rand + 1).rand == Random.new(1).rand
=> true
irb(main):012:0> Random.new(Random.new(5).rand + 1).rand == Random.new(5).rand
=> false
irb(main):013:0> Random.new(Random.new(5).rand + 5).rand == Random.new(5).rand
=> true

For a second, I thought "wow, maybe that's a property of random number generators", but Python and C# fail to reproduce this.

sawa
  • 165,429
  • 45
  • 277
  • 381
Juliano
  • 2,402
  • 1
  • 20
  • 22

1 Answers1

11

You’re probably going to be disappointed with this one. Let’s take a look at the output of rand:

irb(main):001:0> Random.rand
0.5739704645347423

It’s a number in the range [0, 1). Random.new accepts an integer seed.

irb(main):002:0> Random.new(5.5) == Random.new(5)
true

Mystery solved!

Ry-
  • 218,210
  • 55
  • 464
  • 476
  • Note that the OP isn't testing equality between `Random` instances but between floats. A (small) step is missing in your explanation IMHO. – Eric Duminil Feb 07 '17 at 13:22
  • @EricDuminil: The equality was to point out that they have the same state, so of course they’ll produce the same random numbers. (`a == b` for `a.is_a? Random` implies `a.rand == b.rand`.) – Ry- Feb 07 '17 at 13:28
  • It might be obvious to you, but not to the OP or to everyone coming to read your answer. I had to look at `random.c` to check how `Random` equality is defined. My 2c$. – Eric Duminil Feb 07 '17 at 13:30
  • @EricDuminil: If it’s false, it’s true that it wouldn’t tell you anything for sure, but since it’s true one can surmise that equality is defined in the only useful way for `Random` instances. =) – Ry- Feb 07 '17 at 13:31