I am reviewing a code which I believe runs based on probability. I would like to verify that if it is true. Does the following code snippet runs 80% of the time? I dont quite get why use 1000 then if our job is to merely run a code 80% of the time.
if(rand()%1000<1000*0.8){
...
}
It will run approximately 80% of the time.
rand()
returns a number between 0 and RAND_MAX
which is probably 2,147,483,647rand() % 1000
reduces that range to 0-999, although some numbers in the first half or so of the range will be slightly more common because RAND_MAX
is not evenly divisible by 1,0001000 * 0.8
is just 800The use of 1,000 here is arbitrary. A clearer way of representing 80% would be:
if (rand() % 100 < 80)
or just:
if (rand() < RAND_MAX * 0.8)