The open-source Uncommons Maths library by Dan Dyer provides random number generators, probability distributions, combinatorics and statistics for Java.
Among other valuable classes, ExponentialGenerator
has essentially implemented the idea explained by @Alok Singhal. In its tutorial blog, a code snippet is given to simulate some random event that happened on average 10 times a minute:
final long oneMinute = 60000;
Random rng = new MersenneTwisterRNG();
// Generate events at an average rate of 10 per minute.
ExponentialGenerator gen = new ExponentialGenerator(10, rng);
boolean running = true;
while (true)
{
long interval = Math.round(gen.nextValue() * oneMinute);
Thread.sleep(interval);
// Fire event here.
}
Of course, if you prefer to the time unit per second
(instead of a minute
here), you just need to set final long oneMinute = 1000
.
Going deeper into the source code of the method nextValue()
of ExponentialGenerator
, you will find the so-called inverse transform sampling described in Generating_exponential_variates [wiki]:
public Double nextValue()
{
double u;
do
{
// Get a uniformly-distributed random double between
// zero (inclusive) and 1 (exclusive)
u = rng.nextDouble();
} while (u == 0d); // Reject zero, u must be positive for this to work.
return (-Math.log(u)) / rate.nextValue();
}
P.S.: Recently I am using the Uncommons Maths library. Thanks Dan Dyer.