Source of Book
For the textbook, see the note in Github.
Ex5-1-3
Q
The question is too long. So I don't type it. (I have NOT found the PDF version of textbook yet.)
Understand of Q (and changes)
Given a BIASED-RANDOM which output either 0 or 1 whereas the probability to output 0 is p (where 0 < p < 1 ). However, you don't know what actually p is. Give an algorithm (named UNBIASED-RANDOM) that uses BIASED-RANDOM as subroutines and return an unbiased answer (i.e. return 0 with probabilty 1/2, 1 with probabilty 1/2). What is the expected running time of your algorithm as a function p?
In my answer (shown in My Answer section ) of this article, it only answers the requirements of this section instead what the question in textbook asks (shown in Q section).
Answers
My Answer
Implementation 1
Code
C++
#include <cmath>
#include <string> // NOT <cstring>
// eps is 10^(-5)
#define eps ((double) (pow(10,-5)))
// only call BIASED_RANDOM(0,1).
int UNBIASED_RANDOM(double probability)
{
string errorMessage = "ERROR!!! Out of range. Probabilty always should be between 0 and 1.";
if(probability >= 1 - eps)
{
throw errorMessage;
}
if(probability <= 0 + eps)
{
throw errorMessage;
}
/*
I quit I don't come with answer.
*/
}
Expected Running Time
I don't know.
Other Answer
From the website,