Home Java How to use Math.random() method in Java

How to use Math.random() method in Java

The Math.random() method is one of Java’s most commonly used methods for generating a random numeric number. The java.lang class is a built-in class in Java.Math with several mathematical procedures, one of which is Math.random(). Because the Math.random() method is a static method, it can be invoked/called without first constructing a math class instance—the java.lang.Math class offers several methods for performing basic numeric operations such as the exponential, logarithm, square root, and trigonometric functions.

Math.random() method in Java

The java.lang.Math.random() returns a positive-sign double result higher than or equal to 0.0 but less than 1.0. The returned values are picked pseudorandomly from that range with a (roughly) uniform distribution. When this method is invoked for the first time, it creates a single new pseudorandom-number generator, just like the new java.util.Random.

True random numbers and pseudo-random numbers are two types of computer-generated random numbers. External influences are used to generate truly random numbers. For instance, you can use noises in the environment to generate randomization.

However, generating such a truly random number takes time. As a result, we can use pseudo-random numbers generated using a seed value and an algorithm. For the most part, these pseudo-random numbers are sufficient. They can be used in cryptography, making games like dice or cards, and generating OTP (one-time-password) numbers, for example.

This new pseudorandom-number generator is used for all calls to this method and nowhere else. This technique is appropriately synchronized to allow many threads to use it correctly. Having each thread’s pseudorandom-number generator may alleviate conflict if several threads need to generate pseudo-random numbers at a high pace.

Declaration

The declaration for java.lang.Math.random() is is as follows.

public static double random()

Value of the Return

This method returns a pseudo-random double that is less than 1.0 and higher than or equal to 0.0. This article will give you a comprehensive explanation of the following principles linked to the Math.random() method:

What is Math.random(), and how does it work?

It is a built-in method in java.lang package. It is a math class used to generate a double data type random value. The resulting number will be less than 1.0 and larger than or equal to 0.0.

Syntax for Beginners

The following excerpt demonstrates the Math.random() method’s fundamental syntax:

public static double random()  {
}

What is returned by the Math.random() method?

The following expression will help you understand this concept better:

5.0 <= Math.random() < 7.5

You can see that 5.0 is included in the snippet above. However, 7.5 is not. It means that the Math.random() method produces a value ranging from 5.0 to 7.499999999.

How can I use Math.random() to acquire a certain range of values?

Let’s say we wish to generate a random number between 0 and 10. Is that possible? Yes! The Math.random() method in Java may be used to get a certain range of values, and all we have to do is multiply the returned value of the Math.random() method by the desired range. This concept is better understood if you use the expression below:

int randValue = (int) (Math.random() * 10);

The code above will generate a range of values between 0 and 10 at random (10 not included). To include ten as well, the range must be specified as (n+1), i.e., 11:

int randValue = (int) (Math.random() * 11);

The snippet above will now create random numbers between 0 and 10.

How to use Math.random() in Java

Let’s look at the samples below to see how the Java Math.random() method works. We’ll use the Math.random() method to produce two random values in this example:

public class CodeRandomMethod
{  
    public static void main(String[] args)  
    {  
        double numOne = Math.random();  
        double numTwo = Math.random();  
        System.out.println("The First Value is: " + numOne);
        System.out.println("The Second Value is: "+numTwo);
    }
}

Because Math.random() provides a random numeric value, we will get a different number each time we run this code. For example, consider another scenario where you need to generate a random value inside a certain range. We’ll generate an integer value between 0 and 10 (inclusive) in the sample below:

public class CodeRandomMethod {
    public static void main(String[] args) {
        int numOne = (int) (Math.random() * 11);
        System.out.println("The first value is: " + numOne);
    }
}

We will get a distinct random number between the specified range each time we run this program.

We can see from the following code sample that the Math.random() method generates a random integer value inside the desired range, indicating that our application is appropriate. We’ve seen that we can specify a range of values in the examples above, but the beginning value is always zero.

However, we may also specify the initial range/value, in which case the Math.random() method will generate a random number between (initial value + (final value-1)). The following code snippet can help you grasp this concept:

public class CodeRandomMethod {

    public static void main(String[] args) {

        int numOne = 5 + (int) (Math.random() * 11);
        System.out.println(" The first value is: " + numOne);

    }

}

The initial value is “5”, and the final is “11” in the snippet above. The Math.random() method will now create a number between 5 and 15 (5 + (11-1)). The output validates the Math.random() method’s functionality.

package com.codeunderscored;

import java.lang.*;

public class CodeMath {

   public static void main(String[] args) {

      //two double numbers at random
      double xVal = Math.random();
      double yVal = Math.random();
   
      // print the numbers and print the higher one
      System.out.println("The first random number is:" + xVal);
      System.out.println("The second random number is:" + yVal);
      System.out.println("The highest number is:" + Math.max(xVal, yVal));
   }
}

Using the Random class for generating Integers

There are numerous instance methods in the Random class that generates random integers. We’ll look at two instance methods in this section: nextInt(int bound) and nextDouble ().

What is the nextInt(int bound) method, and how do I use it?

nextInt(int bound) returns an int-type pseudo-random integer that is less than the bound value and greater than or equal to zero. The bound argument specifies the range. If we set the bound to 7, for example, nextInt(7) will return an int type value higher than or equal to zero but less than four. The potential outputs of nextInt(7) are 0,1,2,3,4,5,6,7. We should build a random object to access this method because it is an instance method. Let’s give it a shot.

public static void main(String[] args) {

        // creation of a random object
        Random randObject = new Random();

        // it generates random numbers from 0 to 6
        int numVal = randObject.nextInt(7);
        System.out.println(numVal);
    }

What is the nextDouble() method, and how do I utilize it?

The nextDouble() function, like Math.random(), returns a double type pseudo-random integer larger than or equal to zero and less than one.

public static void main(String[] args) {

  // creation of a Random object
  Random randObject = new Random();

  // creates a random number between 0.0 and 1.0.
  double numVal = randObject.nextDouble();
  System.out.println(numVal);
}

Example: Random Numbers Within a Range

Finding random numbers inside a range is a popular use case. Let’s look at an example where we’ll randomly produce a number between 1 and 10.

public class CodeMath {
    public static void main(String[] args) {
        evaluateRandom();
    }

    private static void evaluateRandom() {
        // Generation of  random numbers from 10 to 20 (inclusive) 10 times
        for (int i=10; i<20; i++) {
            System.out.println(
                    (int)randomValueWithinRange(10,20)
            );
        }

    }
    private static double randomValueWithinRange(int smallest, int highest) {
        assert smallest < highest;

        int rangeVals = (highest - smallest) + 1;
        return ((Math.random() * rangeVals) + smallest);
    }
}

Example : Math.random() in Java

class CodeUnderscoredMain {

  public static void main(String[] args) {

    // Math.random()

    // This represents the first random value
    System.out.println(Math.random());  

    // This represents the second random value
    System.out.println(Math.random());  /


    // This represents the third random value
    System.out.println(Math.random());  

  }
}

We can see that the random() method gives three different results in the example above.

Example 2: Produce a random number between fifty and fifty-five

class CodeRandomNumber {

  public static void main(String[] args) {

    int upperBoundValue = 55;
    int lowerBoundValue = 50;

    // upperBound 55 will also be included
    int rangeValue = (upperBoundValue - lowerBoundValue) + 1;

    System.out.println("Random Number values between 50 and 55:");

    for (int i = 0; i < 5; i ++) {

      // generation of a random number
      // (int) conversion of double value to int
      // Math.random() is responsible for generation of values between 50.0 and 55.0
      int random = (int)(Math.random() * rangeValue) + lowerBoundValue;

      System.out.print(random + ", ");
    }

  }
}

Example: Getting to Elements in a Random Array

class CodeRandomMain {
  public static void main(String[] args) {

    // create an array
    int[] arrayVals = {22, 42, 64, 14, 83, 37, 58, 11};

    int lowerBoundValue = 0;
    int upperBoundValue = arrayVals.length;

    // arrayVals.length will excluded
    int range = upperBoundValue - lowerBoundValue;

    System.out.println("List of Random Array Elements:");


    // 5 random array elements
    for (int i = 0; i <= 5; i ++) {

      // get random array index
      int random = (int)(Math.random() * range) + lowerBoundValue;

      System.out.print(arrayVals[random] + ", ");
    }

  }
}

So, which method of generating random numbers should you use?

The random class is used by Math.random(). We can use Math.random() if we want double-type pseudo-random values in our application. Otherwise, we can utilize the random class, which has several methods for generating pseudo-random integers of various sorts, including nextInt(), nextLong(), nextFloat(), and nextDouble().

Conclusion

To generate a pseudo-random double value between 0.0 and 1.0 in Java, use the Math.random() method of the Math class. Math.random() generates a random value. Therefore it will generate a different number each time a program is run.

A random value can be created within a defined range using the Math.random() method. This article has explored several features of the Math.random() function, including what it is, what it returns, how to define a specific range for the random integers, and how to utilize the Math.random() method in Java.

You may also like

Leave a Comment