Let a and b be the results of 2 tosses of the unfair coin. (Where true is heads, false is tails).
Now a is true with a probability of p, a is false with a probability of (1-p) (and the same with b).
| b = true | b = false
a = true | p*p | p*(1-p)
a = false | p*(1-p) | (1-p)(1-p)
Two of these probabilities are equal, a && !b, and !a && b
We can use the following relation to calculate a fair result
if a && !b
true
elsif !a && b
false
else
# try again
end
Greater the value of |p-0.5|
, greater is the number of calls you'd need.
Demonstration using ruby
An unfair coin toss
f=->n { rand < n }
Testing it with p=0.6
irb(main):010:0> (1..10000).count{f[0.6]}
=> 5958
irb(main):011:0> (1..10000).count{f[0.6]}
=> 6088
irb(main):012:0> (1..10000).count{f[0.6]}
=> 5923
Fair coin toss, based on the unfair one
g=->n{a=f[n];b=f[n];a && !b ? true : !a && b ? false : g[n]}
Testing the fair coin toss.
irb(main):021:0> (1..10000).count{g[0.6]}
=> 5005
irb(main):022:0> (1..10000).count{g[0.6]}
=> 5072
irb(main):023:0> (1..10000).count{g[0.6]}
=> 4954
Number of recursive calls made as p increases.
# redefining g to count calls.
irb(main):002:0> g=->n{$c+=1;a=f[n];b=f[n];a&&!b ? true:!a&&b ? false:g[n]}
=> #<Proc:0x259e150@(irb):2 (lambda)>
irb(main):003:0> $c=0
=> 0
irb(main):004:0> (1..10000).count{g[0.99]}
=> 5062
irb(main):005:0> $c
=> 499582
irb(main):006:0> $c=0
=> 0
irb(main):007:0> (1..10000).count{g[0.1]}
=> 4961
irb(main):008:0> $c
=> 55358
irb(main):009:0> $c=0
=> 0
irb(main):010:0> (1..10000).count{g[0.9]}
=> 5003
irb(main):011:0> $c
=> 55013
irb(main):012:0>
If you gave integers
p
andq
and the probability of heads wasp/q
, one wouldn't have to deal with things such as floats not being exact. – None – 2011-02-10T17:49:07.4602This question appears to be off-topic because it is not a programming puzzle – Johannes Kuhn – 2013-12-06T16:20:58.700