4

As described in the documentation, random.random will "return the next random floating point number in the range [0.0, 1.0)"

So what is the chance of it returning a 0?

rovyko
  • 4,068
  • 5
  • 32
  • 44

1 Answers1

9

As per the documentation, it

It produces 53-bit precision

And the Mersenne Twister it is based on has a huge state space, many times large than this. It also routinely passes statistical tests of bit independence (in programs designed to spot patterns in RNG output). The distribution is essentially uniform with equal probability that any bit will be 0 or 1.

The probability of getting precisely 0.0 will be 1 in 2^53 (assuming an unknown internal state)

Neil Slater
  • 26,512
  • 6
  • 76
  • 94
  • Excellent! Will this be consistent across all platforms? Is it possible for the chance to be higher due to constraints made on the algorithm or the precision? – rovyko Sep 16 '16 at 18:27
  • 1
    @dexgecko: I think it will be consistent across most Python versions and platforms, as they all fully implement the Mersenne Twister algorithm in source, it is not an OS or shared library call. You can check this by using e.g. `random.seed( 12345 )` and seeing output from next few calls from `random.random()` - I expect this will be consistent across a wide range of Python implementations. – Neil Slater Sep 16 '16 at 18:31
  • 1
    However if you use `random.SystemRandom` (which you should use anyway) it's a different story. This might heavily depend on OS, CPU and possibly other factors (the entropy source). But then again it should more or less give pretty much the same probability. – freakish Sep 16 '16 at 18:32
  • 1
    @freakish: Depends on the use case. Mersenne Twister is fast and fine statistically for simulations, stochastic solvers etc. Never use it for security purposes though. – Neil Slater Sep 16 '16 at 18:35
  • @NeilSlater True, true, indeed. I guess I'm always thinking about security when I think about randomness. :) – freakish Sep 16 '16 at 18:36