Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

randomness algorithm

Tags:

c++

random

events

I need some help regarding algorithm for randomness. So Problem is.

There are 50 events going to happen in 8 hours duration. Events can happen at random times. Now it means in each second there is a chance of event happening is 50/(8*60*60)= .001736. How can I do this with random generation algorithm?

I can get random number

int r = rand();
double chance = r/RAND_MAX;
if(chance < 0.001736)
    then event happens
else
    no event

But most of times rand() returns 0 and 0<0.001736 and I am getting more events than required.

Any suggestions?


sorry I forget to mention I calculated chance as double chance = (static_cast )(r) / (static_cast)(RAND_MAX);


It removed double from static_cast

double chance = (double)r/(double)(RAND_MAX);

like image 711
anand Avatar asked Aug 06 '26 20:08

anand


1 Answers

Both r and RAND_MAX are integers, so the expression

double chance = r / RAND_MAX;

is computed with integer arithmetic. Try:

double chance = 1.0 * r / RAND_MAX;

which will cause the division to be a floating point division.

However, a better solution would be to use a random function that returns a floating point value in the first place. If you use an integer random number generator, you will get some bias errors in your probability calculations.

like image 187
Greg Hewgill Avatar answered Aug 09 '26 10:08

Greg Hewgill