DEV Community


Posted on

Understanding the basics of seeding Random using ruby

When you create a Random object in ruby without an argument the system-generated seed will be applied to that instance. If you pass in an argument of an integer, that integer will be used as the seed value for that Random instance

random_w_system_seed =
random_w_user_seed =

Seeding affects the order in which a random generator will put out pseudorandom numbers. If two Random instances have the same seed they will put out the same random numbers in the same order when called.

#Here, you can see that the first numbers generated by both 
#instances are the same because they share the same seed
random_same_seed_1 =
random_same_seed_2 =
random_same_seed_1.rand == random_same_seed_2.rand
# => true

#the same applies for comparing the objects, if they will both generate 
#the same number next, when compared it will evaluate to true
random_same_seed_1 == random_same_seed_2
# => true

#Lets call this first Random instance again so that
#it is one step ahead of the second Random instance
# => 0.3163755545817859

#Now the same seed is not returning the same value because
#the first instance is generating the third number in the
#sequence while the second instance is still generating the 
#second number in the sequence
random_same_seed_1.rand == random_same_seed_2.rand
# => false

Whenever a new Random instance is created without passing in a seed a seed will be passed to it by the system. You can check what this seed is with the #seed method. Additionally, you can set the system seed to a specific number so all Random instances generated without an argument share the same seed. You can do this by calling .srand to set the systems seed for random.

#Here, you can get return seeds from Random instances so you can 
#create Random instances with the same seed
random_instance_sys_seed =
# => 124999659906724141071882940163137705973

random_instance_user_seed =
# => 12345

#Here, you can see that using .srand to set the system seed for rand
#called without a user made instance and the user made Random instance
#have the same return value
# => 0.9296160928171479

# => 0.9296160928171479

A class method for Random called .new_seed is what is used to make system seed values if there is no argument given when creating a new Random instance, it can also be called to return arbitrary seeds that are system created.

# => 32130858170704068723128768018578826042

So whats the point? If you want a random number why do you want to seed? The main reason is so even with pseudorandom returns you can have repeatable outcome from a program. This can be used for testing, debugging, teaching, sharing statistical analyses, or writing academic papers.

Top comments (0)