Given a fair coin as input, generate any particular unfair outcome It is easy to generate a fair coin using a unfair coin, but the reverse is harder to accomplish.

Your program will receive one number X (between 0 and 1, inclusive) as input. The input must not simply be hard-coded as a number in the middle of the source code. It must then return a single digit: a 1 with a probability of X and a 0 otherwise.

Your program is only allowed to use one form of random number generator in the source code: int(rand(2)) (or an equivalent), which returns either a zero or a one with equal probability. You can include or access this function as many times as you wish in your code. You also have to provide the function yourself as part of the code.

Your program is not allowed to use any other random number generating functions or external sources (such as time and date functions) that could function as a random number generating function.  It also cannot access any external files or pass the job along to external programs.

This is code golf, the shortest answer wins.
Perl, 37 42 char

($d/=2)+=rand&gt;.5for%!;print$d/2&lt;pop|0


Takes arbitrary probability as a command line argument. Builds a uniform random number in $d and compares it to the input.

Earlier, 52 char solution

$p=&lt;&gt;;do{$p*=2;$p-=($-=$p)}while$--(.5&lt;rand);print$-