Generating numbers which follow Normal Distribution in Java

11,720

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));
  }
} 
Share:
11,720
Manoj
Author by

Manoj

Updated on June 17, 2022

Comments

  • Manoj
    Manoj about 2 years

    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++

  • Manoj
    Manoj over 9 years
    Thanks. This should work. Can you tell me why there is multiplication with variance not with root(variance) in line: return aMean + fRandom.nextGaussian() * aVariance;
  • David Eisenstat
    David Eisenstat over 9 years
    @Manoj Because the author of the snippet never computed a sample variance?
  • Manoj
    Manoj over 9 years
    I guess variance here refers to standard deviation.
  • pjs
    pjs over 9 years
    @rici Your description is wrong on two counts. First, the nextGaussian method produces a standard normal, not a uniform. Second, the standard normal should be scaled by the standard deviation, not by the variance.
  • rici
    rici over 9 years
    @pjs: Guilty as charged.