Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set random seed temporarily, like "new Random()"

Tags:

python

random

In Python, what is the best way to generate some random number using a certain seed but without reseeding the global state? In Java, you could write simply:

Random r = new Random(seed);
r.nextDouble();

and the standard Math.random() would not be affected. In Python, the best solution that I can see is:

old_state = random.getstate()
random.seed(seed)
random.random()
random.setstate(old_state)

Is this idiomatic Python? It seems much less clean than the Java solution that doesn't require "restoring" an old seed. I'd love to know if there's a better way to do this.

like image 338
Sophie Alpert Avatar asked Jun 17 '12 20:06

Sophie Alpert


People also ask

What is set seed in random?

A random seed is a starting point in generating random numbers. A random seed specifies the start point when a computer generates a random number sequence.

How do I randomly generate a random seed in Python?

Python Random seed() Method The random number generator needs a number to start with (a seed value), to be able to generate a random number. By default the random number generator uses the current system time. Use the seed() method to customize the start number of the random number generator.

What does the seed do in random function?

Seed function is used to save the state of a random function, so that it can generate same random numbers on multiple executions of the code on the same machine or on different machines (for a specific seed value). The seed value is the previous value number generated by the generator.

Do you only need to set seed once in R?

So the short answer to the question is: if you want to set a seed to create a reproducible process then do what you have done and set the seed once; however, you should not set the seed before every random draw because that will start the pseudo-random process again from the beginning.


1 Answers

You can instantiate your own Random object.

myrandom = random.Random(myseed)

The random module manages its own instance of Random, which will be unaffected by changes made to myrandom.

like image 119
senderle Avatar answered Oct 11 '22 10:10

senderle