7

Unexpected behavior in the generation of random numbers python

 3 years ago
source link: https://www.codesd.com/item/unexpected-behavior-in-the-generation-of-random-numbers-python.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Unexpected behavior in the generation of random numbers python

advertisements

I have the following code:

import random

rand1 = random.Random()
rand2 = random.Random()

rand1.seed(0)
rand2.seed(0)

rand1.jumpahead(1)
rand2.jumpahead(2)

x = [rand1.random() for _ in range(0,5)]
y = [rand2.random() for _ in range(0,5)]

According to the documentation of jumpahead() function I expected x and y to be (pseudo)independent sequences. But the output that I get is:

x: [0.038378463064751012, 0.79353887395667977, 0.13619161852307016, 0.82978789012683285, 0.44296031215986331]

y: [0.98374801970498793, 0.79353887395667977, 0.13619161852307016, 0.82978789012683285, 0.44296031215986331]

If you notice, the 2nd-5th numbers are same. This happens each time I run the code.

Am I missing something here?


rand1.seed(0)
rand2.seed(0)

You initialize them with the same values so you get the same (non-)randomness. Use some value like the current unix timestamp to seed it and you will get better values. But note that if you initialize two RNGs at the same time with the current time though, you will get the same "random" values from them of course.

Update: Just noticed the jumpahead() stuff: Have a look at How should I use random.jumpahead in Python - it seems to answer your question.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK