Search code examples
pythonrandomcoin-flipping

Small probabilities in Python


How accurate is Python's random() function?

Assume I'd like to make a decision based on a 1 / 234276901 probability coin flip, can I still use a

if random() < 1. / 234276901:

statement?

How accurate would such statement be? (in terms of the actual probability the if will be taken).

Is there a more precise (yet running in reasonable time) way to get such coin flips?


Solution

  • random.random() produces a float value in the range [0.0, 1.0) (meaning that 0.0 is included in the possible values, but 1.0 is not).

    Floating point numbers have 53 bits of precision, so you get 2 ** 53 different 'steps' between 0.0 and 1.0. 53 bits is plenty of precision to represent 1 / 234276901, which only needs about 28 bits:

    >>> 234276901 .bit_length()
    28
    

    So yes, using random.random() < 1 / 234276901 will work, there is plenty of precision left over.