Random nextGaussian() method in Java
In this tutorial, we are going to learn about the nextGaussian() method which is present in the Random class in Java.
It is used to generate the next pseudorandom Gaussian double value with a mean of 0.0 and standard deviation of 1.0 from this random value generator’s sequence. Let’s see some points…
- This method is present in java.util package.
- It does not throw an exception at the time of returning a value.
- The method does not accept any parameter.
- The return type of the method is double, it returns the random Gaussian distributed double value with mean and standard deviation from this Random Generator.
There are various applications of the method:
- It is used in mathematics.
- It is also used in modelling and simulation.
- It also can be used for sampling the packets as it generates clusters of values with mean and standard deviation.
Random nextGaussian() method in Java
Following are the steps we need to follow to achieve our goal:
- Import java.util package.
- Create an object of Random class.
Random random=new Random();
- Create one double variable to store the number generated from the nextGaussian() method.
double value=random.nextGaussian();
- Finally, print the number.
Following is the code for our task:
Example 1:
//import package import java.util.Random; public class nextGaussian { public static void main(String[] args) { //create object of random class Random random=new Random(); //return pseudorandom Gaussian value double value=random.nextGaussian(); //print the value System.out.println("Random Gaussian value: "+value); } }
Output 1:
Random Gaussian value: -0.09891103710685835
Output 2:
Random Gaussian value: 0.6904242633193539
Example 2:
import java.util.Random; public class nextGaussian { public static void main(String[] args) { Random random=new Random(); for(int i=0;i<5;i++) { double value=random.nextGaussian(); System.out.println("Random Gaussian value: "+value); } } }
Output:
Random Gaussian value: -2.270553436367474 Random Gaussian value: 0.06981849943114561 Random Gaussian value: -0.9181225040401672 Random Gaussian value: 0.3383560104821811 Random Gaussian value: -1.1352213899667787
This is how we can implement nextGaussian method in Java. I hope you find this tutorial useful.
Also, read: Find the second-highest number in an ArrayList in Java
Leave a Reply