Reputation: 314
I want to generate numbers(randomly) such that the numbers follow the Normal distribution of given mean and variance. How can I achieve this?
It would be better if you can give this in context of Java. One might look in these answers for help: but they are not precise. Generate random numbers following a normal distribution in C/C++
Upvotes: 6
Views: 13331
Reputation: 20019
Shamelessly googled and taken from: http://www.javapractices.com/topic/TopicAction.do?Id=62
The 'magic' happend inside Random.nextGaussian()
import java.util.Random;
/**
Generate pseudo-random floating point values, with an
approximately Gaussian (normal) distribution.
Many physical measurements have an approximately Gaussian
distribution; this provides a way of simulating such values.
*/
public final class RandomGaussian {
public static void main(String... aArgs){
RandomGaussian gaussian = new RandomGaussian();
double MEAN = 100.0f;
double VARIANCE = 5.0f;
for (int idx = 1; idx <= 10; ++idx){
log("Generated : " + gaussian.getGaussian(MEAN, VARIANCE));
}
}
private Random fRandom = new Random();
private double getGaussian(double aMean, double aVariance){
return aMean + fRandom.nextGaussian() * aVariance;
}
private static void log(Object aMsg){
System.out.println(String.valueOf(aMsg));
}
}
Upvotes: 5