Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating numbers which follow Normal Distribution in Java

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

like image 970
Manoj Avatar asked Sep 28 '22 09:09

Manoj


1 Answers

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));
  }
} 
like image 140
Rob Audenaerde Avatar answered Oct 05 '22 08:10

Rob Audenaerde