Reputation: 358
I am trying to implement a random number generator in my Java program. I was using Math.random()
but that didn't seem to work very well. Then I tried using SecureRandom, but that took too long for my game. However, I came across this generator, the MersenneTwisterRNG random number generator. It seems to be what I want; fast, but still random.
However, I have not been writing in Java for very long, only 2 months, and I cannot make heads nor tails of the API. If anyone could help explain to me how to use this in my code, it would be appreciated. Or, if you happen to know of a simpler, but similar, random number generator, I would be interested in that as well. The API is here.
Upvotes: 0
Views: 241
Reputation: 18533
How to use the MersenneTwisterRNG API:
import java.util.Random;
import org.uncommons.maths.random.MersenneTwisterRNG;
This lets you access the classes using their short names.
Random rand = new MersenneTwisterRNG();
This creates a new MersenneTwisterRNG. We put it into a variable of type Random so that we can swap it out for another RNG easily if needed.
double x = rand.nextDouble();
This behaves the same as Math.random(), and returns a double-precision floating-point number between 0.0 and 1.0.
int n = rand.nextInt(10);
This generates a random number between 0 (inclusive) and 9 (inclusive), i.e. 0 <= n < 10. This is useful for a lot of integer algorithms.
Upvotes: 1