Java Random.nextGaussian() – Examples

In this tutorial, we will learn about the Java Random.nextGaussian() method, and learn how to use this method to generate a random Gaussian double value, with the help of examples.

nextGaussian()

Random.nextGaussian() returns the next pseudorandom, Gaussian (“normally”) distributed double value with mean 0.0 and standard deviation 1.0 from this random number generator’s sequence.

Syntax

The syntax of nextGaussian() method is

</>
Copy
Random.nextGaussian()

Returns

The method returns double value.

Example 1 – nextGaussian()

In this example, we will create an object random of Random class type. We will call nextGaussian() on this Random object to get the next Gaussian double value. We shall print it to console.

Java Program

</>
Copy
import java.util.Random;

public class Example{ 
    public static void main(String[] args) {
    	Random random = new Random();
    	double g = random.nextGaussian();
    	System.out.println("Next random gaussian value is : " + g);
    }
}

Output

Next random gaussian value is : 0.05262116402960923

Output may vary, since the gaussian value is generated randomly.

Example 2 – nextGaussian()

In this example, we will generate random gaussian values in a for loop using nextGaussian().

Java Program

</>
Copy
import java.util.Random;

public class Example{ 
    public static void main(String[] args) {
    	Random random = new Random();
    	for (int i=0; i < 10; i++) {
    		System.out.println(random.nextGaussian());
    	}
    }
}

Output

2.2700954197614904
0.5557929749714717
-0.17651117370106462
2.745661662212665
-1.3766539745359516
0.7951864007924534
0.6366774518985259
0.9478975417383658
-0.23375030243784262
0.48644030936202814

Output may vary, since the gaussian value is generated randomly.

Conclusion

In this Java Tutorial, we have learnt the syntax of Java Random.nextGaussian() method, and also learnt how to use this method with the help of examples.