0

I would like to add to this random function a parameter which represent odds of returning true for example rand_num(80) will give 80% odds of returning true.

bool rand_num()             // randomize 0 or 1
{
int result =0;
srand(time(NULL));
result = (rand()%2);

return result;

}   

Thanks.

Mike L
  • 1,955
  • 2
  • 16
  • 18

3 Answers3

3

So two people have given similar answers that are simple mod. Both are wrong. Correct version:

bool randX(int X)
{
    do {
       int rnd = rand() & 127;
       if (rnd < X) return true;
       if (rnd >= X && rnd < 100) return false;
    } while (1);
}

Please note that using mod destabilizes as the distribution of rand() is not smooth over arbitrary mod.

Joshua
  • 40,822
  • 8
  • 72
  • 132
1

(EDIT: It's been suggested that this answer is wrong because the modulo introduces a bias. In reality, if your application is sensitive enough to be affected by the bias, then you shouldn't be using rand() in the first place. This is based on statistical analysis rather than hypothetical conjecture.)

Modulo your rand() output by 100, and if the result is less than or equal to the odds, return true.

As a side note, you're not really using srand() correctly. You should typically call it once at the start of your program, rather than every time you generate a random number.

Peter Bloomfield
  • 5,578
  • 26
  • 37
  • 2
    see [this question](http://stackoverflow.com/q/10984974/10396) for why this is biased: – AShelly Nov 08 '13 at 18:30
  • The biasing issue is definitely a fair point. However, I'd argue that `rand()` is typically such a poor generator (in terms of uniformity) that the effect of bias will be trivial for most applications which are likely to use it. – Peter Bloomfield Nov 08 '13 at 19:16
  • Sorry I neglected that. I'm used to a fixed rand(). – Joshua Nov 09 '13 at 21:07
1
bool randOdds(float odds) //odds should be a percentage between 0 and 1
{
   return ( rand()*(1.0/RAND_MAX) <= odds );
}
AShelly
  • 34,686
  • 15
  • 91
  • 152
  • Well here's another way. I use a loop, you use the FPU. Choose your poison I guess. – Joshua Nov 08 '13 at 18:24
  • This answer is provably non-uniform; it's basically a hash function mapping all possible values of `rand()` onto either `0` or `1`. Since there are `1< – Quuxplusone Nov 19 '13 at 06:11
  • @Quuxplusone: True but it's never off by more than odds / RAND_MAX. – Joshua Nov 20 '13 at 22:08
  • @Joshua Sure, and it takes a `float`, which could be a convenient API if you want something to happen with probability (roughly) `sqrt(0.5)`. (I'm not being sarcastic; floating point *is* nice sometimes.) But it has the exact same non-uniformity problem as the naive `rand() % 100 < 80` approach, for the OP's use-case. ...wait, aren't you the @Joshua who wrote the "beware of non-uniformity" answer above? :D – Quuxplusone Nov 21 '13 at 00:17