Math.random Java Tutorial

488 views

1. What is java.lang.Math.random() in java?

Today we’ll analyze how the Math.random() method works in Java. The Math.random() method is a function of the Math class that accepts zero arguments and returns a pseudorandom number between 0(inclusive) and 1(exclusive).

2. Simple Math.random() example

Below you can find a simple example of using this method:

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

        //The function returns a random number between 0(inclusive) and 1(exclusive)
        for (int i = 0; i < 5; i++)
            System.out.println(Math.random());
    }
}

The main method just calls the Math.random method 5 times using a for loop and prints the result.

The output could be:

0.1209483334305419
0.5720587874439879
0.7066503715407789
0.315074080697907
0.9527311172606369

3. How to use Math.random in Java with upper and lower limits

You can adjust math.random in java in order to get a random number (integer or decimal), inside the desired range.

The formula for a random double in [lowerLimit, upperLimit) is the following:

 result  = lowerLimit + Math.random() * (upperLimit - lowerLimit) 

Let’s explain the formula:

We set the lower limit since we want the minimum number that will be generated, to be equal to the lower limit.

Then we want to set the upperLimit. Since the Math.random() method returns a number in [0,1), if we multiply this number by a factor of the upperLimit number, then it is possible to get a number higher than the lowerLimit since lowerLimit plus upperLimit is greater or equal than the upperLimit. The solution to this is to subtract the lowerLimit, and then multiply it by Math.random().

Should you like to find a random integer inside the interval [lowerLimit, upperLimit], the formula is the following:

result  = (int) (lowerLimit + Math.random() * (upperLimit - lowerLimit + 1))

You can find a detailed example below.

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

        // Get a random number between 1 and a number less than 100
        double a = 1 + Math.random()*(100 - 1);
        System.out.println(a);

        // Get a random number between 42.5 and a number less than 57.2
        double b = 42.5 + Math.random()*(57.2 - 42.5);

        // print the result
        System.out.println(b);

        //The lower and upper limit can be adjusted according to the following formula:
        // double x = lowerLimit + Math.random()*(upperLimit - lowerLimit)  returns a number in [lowerLimit, upperLimit)
        double lowerLimit = 1000;
        double upperLimit = 1100;
        System.out.printf("A random double in [%f, %f) : %f \n",lowerLimit,upperLimit,getRandomDoubleExclusive(lowerLimit,upperLimit));
        System.out.printf("A random integer in [%f, %f) : %d \n",lowerLimit,upperLimit,getRandomIntExclusive(lowerLimit,upperLimit));

        // To include the upper limit for integers, the formula is:
        // int x = lowerLimit + Math.random()*(upperLimit - lowerLimit + 1)  returns a number in [lowerLimit, upperLimit]
        lowerLimit = 1340;
        upperLimit = 1350;

        System.out.printf("A random integer in [%f, %f] : %d \n",lowerLimit,upperLimit,getRandomIntInclusive(lowerLimit,upperLimit));

    }

    public static double getRandomDoubleExclusive(double lowerLimit, double upperLimit){
        return lowerLimit + Math.random() * (upperLimit - lowerLimit);
    }

    public static int getRandomIntExclusive(double lowerLimit, double upperLimit){
        return (int)(lowerLimit + Math.random() * (upperLimit - lowerLimit));
    }

    public static int getRandomIntInclusive(double lowerLimit, double upperLimit){
        return (int)(lowerLimit + Math.random() * (upperLimit - lowerLimit + 1));
    }

}

The output could be:

99.25672879864882
45.1466094039262
A random double in [1000.000000, 1100.000000) : 1080.026684 
A random integer in [1000.000000, 1100.000000) : 1021 
A random integer in [1340.000000, 1350.000000] : 1343

Let’s explain what happened here:

Line 5: We get a random double in the range [1, 100).

Line 9: We get a random double in the range [42,5, 57,2).

Line 18: We get a random double in the range [lowerLimit, upperLimit).

Line 19: We get a random integer in the range [lowerLimit, upperLimit).

Line 26: We get a random integer in the range [lowerLimit, upperLimit].

Finally, after the main method, you can find the functions we used, according to the formulas described above.

4. How to use Math.random in java – A real-world example

The method analyzed above can be used in various applications. You can generate random passwords, random IDs, or random Usernames. It can also be used to add randomness to games of all kinds (Tetris could be an example).

Below you can find an example of a program that simulates a coin toss and rolling of a die, for a number of times provided by the user.

import java.util.Scanner;

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

        Scanner scanner = new Scanner(System.in);

        System.out.println("Choose number of times to roll a die");
        int number = scanner.nextInt();
        for (int i = 0;i < number; i++){
            System.out.println(getRandomIntInclusive(1,6));
        }
        System.out.println("Choose number of times to toss a coin");
        number = scanner.nextInt();
        for (int i = 0; i < number; i++){
            System.out.println(getCoinToss());
        }

    }
    // The method in the previous example
    public static int getRandomIntInclusive(double lowerLimit, double upperLimit){
        return (int)(lowerLimit + Math.random() * (upperLimit - lowerLimit + 1));
    }
    // To simulate a coin toss, get a random integer in [0, 1], and if it is 0, return Heads, else, return Tails
    public static String getCoinToss(){
        int result = getRandomIntInclusive(0,1);
        if(result == 0)
            return "Heads";
        else
            return "Tails";

    }

}

Let’s explain the code above.

Line 8: We prompt the user to input the number of times to roll a die

Line 11: We print the result using the method described in section 3.

Line 16: We simulate a coin toss based on the number provided again by the user, using the getCoinToss() method.

Line 25: The method just uses the getRandomIntInclusive() method to get a random number in [0,1] and returns “Heads” or “Tails” based on the result.

5. Conclusion

This was an example for Math.random() method. You can find the source code on our GitHub page.

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

Related Posts