Reputation: 11309
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);
Upvotes: 1
Views: 508
Reputation: 54475
Exactly 50, or on average 50?
You might want to look into the Exponential distribution and find a library for your language that supports it.
The Exponential distribution will give you the intervals between events that occur randomly at a specified average rate.
You can "fake" it with a uniform RNG as follows:
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;
Upvotes: 2
Reputation: 11910
Why not create a 28,800 element list and pull 50 elements from it to determine the time of the events? This does assume that 2 events can't occur at the same time and each event takes 1 second of time. You can use the random number generator to generate integer values between 0 and x so that it is possible to pick within the limits.
Upvotes: 0
Reputation: 53366
And you have the 50 seconds.
Note that you can have duplicates.
Upvotes: 2
Reputation: 11831
If you choose whether an event will happen in each second, you have a change of 0 events occurring or 8*60*60 events occurring. If 50 events is a constraint, choose 50 random times during the 8 hour period and store them off.
Upvotes: 7
Reputation: 993015
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.
Upvotes: 7