import random
import matplotlib.pyplot as plt
nums = []
mu = 0
sigma = 2
for i in range(100):
temp = random.gauss(mu, sigma)
nums.append(temp)
plt.plot(nums)
plt.show()
Here, I haven't declared the seed value. So, will it consider
different seed values at each iteration of i
? In this kind of
simulation, or say in long Monte Carlo simulations, is it recommended to
choose different values of seeds instead of a particular fixed seed
value ?
CodePudding user response:
If you don't initialize the pseudo-random generator using random.seed()
then Python will attempt to get a random seed from the operating system, failing that it will use the system time.
List of random numbers without a seed:
import random
for i in range(5):
print(random.randint(1,50))
Output:
19
44
33
12
42
If you want reproducible results for your experiment/simulation then it's advisable to initialize the pseudo-random number generator with a known seed value.
Reproducible list of random numbers using a seed value:
import random
for i in range(5):
random.seed(13)
print(random.randint(1,50))
Output:
17
17
17
17
17
This demonstrates that Python's random
module does not produce truly random numbers, it's predictable if you know the seed value.
CodePudding user response:
No, random
does not reseed unless you tell it to.
random
implements the Random
class for its operations. This class seeds itself on initialization - either with a default seed or one you supply. You can reseed with the .seed
method but that's not typically done with a Random
object you create yourself.
The module then creates one instance of Random
and assigns its methods to module level variables. When you call random.gauss
, that's really a method on this object. This object uses the default seed algorithm. If you don't want the default algorithm or if you want to seed with a known value for reproducible random numbers, you can call random.seed(yourvalue)
.
But that whole reproducibility thing is dodgy on the default random object. Other things in your system also calling random will mess up your supposedly reproducible numbers. If you want reproducibility (maybe for testing?), create your own random.Random
objects.