R B
R B

Reputation: 543

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?

Upvotes: 0

Views: 326

Answers (2)

Assem
Assem

Reputation: 12077

If you want to get a coin flip of 1 / 234276901, use random.random() like this:

>>> floor(random.random() * 234276901)

since random() gives real values between 0 and 1, we should multiply it by your max to stretch the interval than rounding values to convert them to integers.


You can also use random.randint():

>>> random.randint(1,234276901)

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121296

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.

Upvotes: 1

Related Questions