SHARE
TWEET

Random bit with parameterized bias

fgrieu Mar 23rd, 2013 33 Never
  1. // given get_random_bit() returning unbiased 0 or 1,
  2. // return 0 or 1 with specified bias (odds of a 1 is bias)
  3. // credit: Poncho's http://crypto.stackexchange.com/a/6508/555
  4. // 2013-03-23 modified to recover the original's numerical stability
  5. int biased_bit(double bias) {
  6.     while (bias>0) {
  7.         if (bias >= 1) return 1;
  8.         bias = 2*bias-get_random_bit();
  9.     }
  10.     return 0;
  11. }
RAW Paste Data
Top