Unexpected behavior when generating random numbers in python

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 jumpahead() function documentation, I expected x and y be (pseudo) independent sequences. But I get the result:

 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 number will be the same. This happens every time I run the code.

Did I miss something?

+4
source share
2 answers
 rand1.seed(0) rand2.seed(0) 

You initialize them with the same values ​​to get the same (non) randomness. Use a value like the current unix timestamp to sow it and you will get better values. But keep in mind that if you simultaneously initialize two RNGs at the same time as the current time, you will get the same "random" values ​​from them.

Update: just noticed jumpahead() : see How to use random.jumpahead in Python - it seems to answer your question.

+4
source

I think there is an error, the python documentation does not make it as clear as it should.

The difference between the two parameters for jumpahead is 1, which means that you are guaranteed to get only 1 unique value (which happens). if you need more values, you need larger parameters.

EDIT: Further explanation

Initially, as the name suggests, jumpahead just jumped forward in sequence. It is clear that in this case, when a jump of 1 or 2 places forward in the sequence will not lead to independent results. As it turned out, jumping forward in most random number generators is inefficient. For this reason, the python only approaches forward. Since its only exemplary, python can implement a more efficient algorithm. However, the method β€œpretends” to go forward; passing two identical integers will not lead to a completely different sequence.

To get different sequences, you need integers to be passed far apart. In particular, if you want to read a million random numbers, you need to separate your jumps by a million.

As a final note, if you have two random number generators, you only need to go to one of them. You can (and should) leave the other in its original state.

+1
source

Source: https://habr.com/ru/post/1341243/


All Articles