Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does random work like this in Ruby?

Tags:

random

ruby

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.

like image 827
Juliano Avatar asked Feb 07 '17 13:02

Juliano


1 Answers

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!

like image 173
Ry- Avatar answered Dec 09 '22 03:12

Ry-