## problem with Random.nextGaussian()

Tags: java random
By : Bharath
Source: Stackoverflow.com
Question!

Random.nextGaussian() is supposed to give random no.s with mean 0 and std deviation 1. Many no.s it generated are outside range of [-1,+1]. how can i set so that it gives normally distributed random no.s only in the range -1 to 1.

By : Bharath

This code will display count number of random Gaussian numbers to console (10 in a line) and shows you some statistics (lowest, highest and average) afterwards.

If you try it with small count number, random numbers will be probably in range [-1.0 ... +1.0] and average can be in range [-0.1 ... +0.1]. However, if count is above 10.000, random numbers will fall probably in range [-4.0 ... +4.0] (more improbable numbers can appear on both ends), although average can be in range [-0.001 ... +0.001] (way closer to 0).

``````public static void main(String[] args) {
int count = 20_000; // Generated random numbers
double lowest = 0;  // For statistics
double highest = 0;
double average = 0;
Random random = new Random();

for (int i = 0; i < count; ++i) {
double gaussian = random.nextGaussian();
average += gaussian;
lowest = Math.min(gaussian, lowest);
highest = Math.max(gaussian, highest);
if (i%10 == 0) { // New line
System.out.println();
}
System.out.printf("%10.4f", gaussian);
}
// Display statistics
System.out.println("\n\nNumber of generated random values following Gaussian distribution: " + count);
System.out.printf("\nLowest value:  %10.4f\nHighest value: %10.4f\nAverage:       %10.4f", lowest, highest, (average/count));
}
``````
By : Hardzsi

A Gaussian distribution with a mean 0 and standard deviation one means that the average of the distribution is 0 and about 70% of the population lies in the range [-1, 1]. Ignore the numbers that are outside your range -- they form the fringe 16% approx on either side.

Maybe a better solution is to generate a distribution with `mean=0` and `std.dev=0.5`. This will give you a distribution with about 96% of the values in the range [-1, 1].

An even better solution is to work backward as above and use the idea that approx. 99.7% of the values lie in the 3-sigma range: use a `std.dev = 1/3`. That will almost nullify the amount of not-so-useful values that you are getting. When you do get one, omit it.

Of course, if you are working on a math intensive product, all of this bears no value.

Gaussian distribution with your parameters. is has density e^(-x^2/2). In general it is of the form e^(linear(x)+linear(x^2)) which means whatever settings you give it, you have some probability of getting very large and very small numbers.
You are probably looking for some other distribution.

By : SurDin