from 算法导论CLRS
假设有一个过程Biased-Random,他可以返回0或者1,但返回0的概率是p,返回1的概率是1-p,利用这个过程作为子程序,请设计一个过程以1/2的概率返回0或者1
To get an unbiased random bit, given only calls to BIASED-RANDOM, call BIASED-RANDOM twice. Repeatedly do so until the two calls return different values, and when this occurs, return the first of the two bits:
UNBIASED-RANDOM
while TRUE
do
x ← BIASED-RANDOM
y ← BIASED-RANDOM
if x _= y
then return x
To see that UNBIASED-RANDOM returns 0 and 1 each with probability 1/2, observe
that the probability that a given iteration returns 0 is
Pr {x = 0 and y = 1} = (1 − p)p ,
and the probability that a given iteration returns 1 is
Pr {x = 1 and y = 0} = p(1 − p) .
(We rely on the bits returned by BIASED-RANDOM being independent.) Thus, the probability that a given iteration returns 0 equals the probability that it returns 1. Since there is no other way for UNBIASED-RANDOM to return a value, it returns 0 and 1 each with probability 1/2.
Assuming that each iteration takes O(1) time, the expected running time of UNBIASED-RANDOM is linear in the expected number of iterations. We can view each iteration as a Bernoulli trial, where .success. means that the iteration returns a value. The probability of success equals the probability that 0 is returned plus the probability that 1 is returned, or 2p(1 − p). The number of trials until a success occurs is given by the geometric distribution, and by equation (C.31), the expected number of trials for this scenario is 1/(2p(1 − p)).
此处用到一个结论,在伯努利试验中,一个以p概率发生的时间,在取得一次成功之前一共要进行多少次实验?下面给出简要的说明,详细参考CLRS
设X为取得一次成功所要进行的实验次数,则X属于{1,2,。。。}
Pr(X=k)=q^(k-1)*p (q=1-p)
E(X)=sum_{k=1}^{infinity} k Pr(X=k) = 1/p