What is Random.nextGaussian method in Java?
nextGaussian is an instance method of the Random class that is used to get a double value chosen from a Gaussian/Normal distribution with mean as 0.0 and standard deviation as 1.0.
What is Gaussian or Normal distribution?
The Gaussian distribution, also known as the Normal distribution, is a symmetric probability distribution centered on the mean, indicating that data near the mean occur more frequently than data far from it. The normal distribution will appear as a bell curve on a graph. The following example image shows what a bell curve looks like when plotted on a graph.
The Random class is defined in the java.util package. To import the Random class, check the following import statement.
import java.util.Random;
Syntax
public synchronized double nextGaussian()
Parameters
The method accepts no parameters.
Return value
This method returns the next pseudorandom taken from a Gaussian distribution.
Code
import java.util.Random;public class Main{public static void main(String[] args) {//create an object of the Random classRandom random=new Random();for(int i=0;i < 5; i++){// Generate the pseudorandom Gaussian valuedouble value=random.nextGaussian();//print the valueSystem.out.println("Random Gaussian value: "+value);}}}
Explanation
- Line 1: We import the relevant packages.
- Line 8: We create an object of the
Randomclass. - Line 10: We define a
forloop that runs the code block within it for five iterations. - Line 13: We generate the pseudorandom Gaussian value using the
nextGaussian()method. - Line 16: We print the generated pseudorandom Gaussian value.