user324 user324 - 4 years ago 113
Python Question

How exactly does random.random() work in python?

I am a bit confused about how the random.random() function works in python.

The docs say that it 'Return the next random floating point number in the range [0.0, 1.0)'.
I understand that pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator. So I think that's what 'next random floating point' means here. (Please correct me if I am wrong)

But when I saw the source code of the random library, random function is not defined in the

class Random
. Instead, its defined in the
class SystemRandom
as follows (line 671 of the code):

def random(self):
"""Get the next random number in the range [0.0, 1.0)."""
return (int.from_bytes(_urandom(7), 'big') >> 3) * RECIP_BPF


If I understand this correctly, this function generates a random number using os.urandom. Which, according to the documentation, returns random bytes from an OS-specific randomness source. So this will not give the 'next' floating point random number.

How are the two connected? or are they two different things?

I am quite confused here. Any kind of help would be appreciated.

Thanks!

Answer Source

random.random() is actually defined here:

random = _inst.random

However, it is just a reference to C implementation.

Here is a quote from the source:

General notes on the underlying Mersenne Twister core generator:

  • The period is 2**19937-1.
  • It is one of the most extensively tested generators in existence.
  • The random() method is implemented in C, executes in a single Python step, and is, therefore, threadsafe.

You probably want to look at the article on Mersenne Twister. To speak briefly, the state of the generator is not the same as "previous number", it is much more complicated thing. So you are wrong in «…pseudo-random number generators work by performing some operation on a value. Generally this value is the previous number generated by the generator».

As for SystemRandom.random(), it is in a way unrelated to random.random(). It is possible in Python that function with the same name imported from different modules are different, so you can't rely on function's name here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download