Skip to content
Advertisement

Coin flip based on randint returns false mostly?

I am writing a game in python using Pygame. In the game, I am setting a variable to a random value of either True or False using this statement:

(False, True)[random.randint(0, 1)]

After running this 2 to 3 times, it kept returning False. At first, I thought that this was probably a coincidence, but after running this like 10 times, it returned True just one time.

Was this all just a big coincidence, or is there an actual reason behind this disparity?

Just in case you need to know this, I am using the built-in random library

Advertisement

Answer

It’s just a coincidence. The nature of random chance is that you’re more likely to get “unrandom”-looking results the smaller the sample size is. Luckily with a computer program it’s very easy to do tests with very large sample sizes.

>>> import random
>>> import collections
>>> collections.Counter((False, True)[random.randint(0, 1)] for _ in range(10))
Counter({False: 6, True: 4})
>>> collections.Counter((False, True)[random.randint(0, 1)] for _ in range(100))
Counter({False: 52, True: 48})
>>> collections.Counter((False, True)[random.randint(0, 1)] for _ in range(1000))
Counter({True: 528, False: 472})
>>> collections.Counter((False, True)[random.randint(0, 1)] for _ in range(10000))
Counter({False: 5047, True: 4953})
>>> collections.Counter((False, True)[random.randint(0, 1)] for _ in range(100000))
Counter({False: 50288, True: 49712})
>>> collections.Counter((False, True)[random.randint(0, 1)] for _ in range(1000000))
Counter({True: 500047, False: 499953})

The more times we flip the coin, the closer to even the distribution tends to get.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement