Random Algorithm

I need help regarding the randomness algorithm. So there is a problem.

50 events will take place within 8 hours. Events can happen at arbitrary times. This now means that every second the probability of an event is 50 / (8 * 60 * 60) = .001736. How can I do this with a random generation algorithm?

I can get a random number

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

      

But most of the times rand () returns 0 and 0 <0.001736 and I get more events than I need.

Any suggestions?


Sorry, I forgot to mention I was counting on double chance = (static_cast) (r) / (static_cast) (RAND_MAX);


Removed double from static_cast

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

+1


source to share


5 answers


  • Create a list of 50 numbers.
  • Fill them in with a random number from 1 to 8 * 60 * 60.
  • Sort them

And you have 50 seconds.



Please note that you may have duplicates.

+2


source


Both r

and RAND_MAX

are integers, so the expression

double chance = r / RAND_MAX;

      

calculated using integer arithmetic. Try:



double chance = 1.0 * r / RAND_MAX;

      

which will cause the division to be 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 bias errors in your probabilistic calculations.

+7


source


If you choose whether an event occurs every second, you will have a change of 0 events or 8 * 60 * 60 events. If 50 events are a limit, pick 50 random times within an 8 hour period and save them.

+7


source


Exactly 50 or on average 50?

You might want to look into Exponential Distribution and find a library for your language that supports it.

Exponential distribution will give you the intervals between events that happen randomly at a given average rate.

You can "fake" it with a homogeneous RNG like this:

    double u;
    do
    {
        // Get a uniformally-distributed random double between
        // zero (inclusive) and 1 (exclusive)
        u = rng.nextDouble();
    } while (u == 0d); // Reject zero, u must be +ve for this to work.
    return (-Math.log(u)) / rate;

      

+2


source


Why not create a list of 28,800 items and pull 50 items out of it to time the events? This assumes that 2 events cannot happen at the same time, and each event takes 1 second of time. You can use a random number generator to generate integer values ​​from 0 to x so you can choose between.

0


source







All Articles