# Life isn't fair...

…but if you have an unfair coin, you can fix it!

Based on this post over at Lauren Ipsum, you can use statistics to make any unfair coin (defined as something that can return either heads or tails with some arbitrary but constant percent chance) into a fair one with a 5050 chance of heads or tails.

If you look at it, it’s easy enough to make sense of the math. If you have a coin with a 70% chance of flipping heads, for example, you have the following outcomes when you flip the coin twice:

Tails, Tails 9%

The neat bit is that it’s equally likely to get either heads than tails or tails than heads. So all you have to do is flip the coin over and over in pairs until you get a pair where the two results are different, then return the first of the pair. Voila, instant fair coin.

Here’s a nice Python script demonstrating the idea:

import random

class Coin(object):
def __init__(self, r):
self.r = r
self.f = 0

def flip(self):
self.f += 1
return random.random() < self.r

if __name__ == '__main__':
for tries in xrange(5):
r = random.random()
print 'Generating a coin with r = %s' % r

c = Coin(r)

h = 0
t = 0
for i in xrange(10000):
while True:
a = c.flip()
b = c.flip()

if a != b:
if a:
h += 1
else:
t += 1
break

print '''
=== Results ===
tails: %d (%.2f%%)
flips: %d
''' % (h, 100.0 * h / (h + t), t, 100.0 * t / (h + t), c.f)

If you run it a few time, here’s the output:

=== Results ===
tails: 4949 (49.49%)
flips: 53850

Generating a coin with r = 0.0305335132684

=== Results ===
tails: 4962 (49.62%)
flips: 344130

Generating a coin with r = 0.953169761122

=== Results ===
tails: 4953 (49.53%)
flips: 224368

Generating a coin with r = 0.186813443725

=== Results ===
tails: 4922 (49.22%)
flips: 65848

Generating a coin with r = 0.717615022909

=== Results ===