6

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

Community
  • 1
  • 1
Manoj
  • 314
  • 1
  • 2
  • 12
  • There is actual code in some of the answers to the linked question, plus a link to a wikipedia page with actual code. Since the code works and is trivial to convert to Java, I don't see what is "imprecise". – rici Apr 01 '15 at 15:59
  • possible duplicate of [Generate random numbers following a normal distribution in C/C++](http://stackoverflow.com/questions/2325472/generate-random-numbers-following-a-normal-distribution-in-c-c) – rici Apr 01 '15 at 16:00
  • Use Java's builtin `nextGaussian()` (from `java.util.Random`), multiply it by the square root of the variance, and add the mean. – pjs Apr 01 '15 at 17:37

1 Answers1

5

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));
  }
} 
Rob Audenaerde
  • 19,195
  • 10
  • 76
  • 121
  • 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; – Manoj Apr 01 '15 at 11:41
  • 1
    @Manoj Because the author of the snippet never computed a sample variance? – David Eisenstat Apr 01 '15 at 11:55
  • I guess variance here refers to standard deviation. – Manoj Apr 01 '15 at 12:50
  • @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. – pjs Apr 01 '15 at 17:34
  • @pjs: Guilty as charged. – rici Apr 01 '15 at 17:40