Monday, February 20, 2017

Java Programming: Generating random numbers using Math.random()


If you’re working on a program or a game that relies on generating random numbers (e.g. throwing dice can have possible values of 1 to 6), then you can use Java’s built-in function Math.random(). This method returns a pseudorandom positive double number greater than or equal to 0.0 and less than 1.0 (inclusive of 0 but exclusive of 1).

The following example will show the different usage of Math.random().

Example
public class MathRandomDemo {

     public static void main(String[] args){
         
         // Generate random double number between 0.0 (inclusive) and 1.0 (exclusive)
         double x = Math.random();
         System.out.println("Random double number between 0.0 (inclusive) and 1.0 (exclusive): " + x);
         
         // Generate random double number between 0.0 (inclusive) and 10.0 (exclusive)
         double y = Math.random() * 10.0;
         System.out.println("Random double number between 0.0 (inclusive) and 10.0 (exclusive): " + y);
         
         // Generate random integer number between 1 (inclusive) and 6 (inclusive)
         int z = (int) (Math.random() * 6) + 1;
         System.out.println("Random integer number between 1 (inclusive) and 6 (inclusive): " + z);
     }
}

Output

Random double number between 0.0 (inclusive) and 1.0 (exclusive): 0.340407647793009
Random double number between 0.0 (inclusive) and 10.0 (exclusive): 9.048673266441012
Random integer number between 1 (inclusive) and 6 (inclusive): 3

In the example above, if you want to generate a double value greater than or equal to 0.0 but less than 10.0, then you just need to multiply the result of Math.random() with 10.0. This will return random numbers from 0.0 to 9.99. If you want to include 10.0 on the results, then you need to multiply Math.random() with 11.0 instead.

Let’s say you want to specify a minimum and maximum range to the generated random number, then all you have to do is to multiply Math.random() with the maximum value and add the minimum value to its result. In the example above, the minimum value is 1 and maximum value is 6, so we simply do (Math.random() * 6) + 1 to generate numbers from 1 to 6.

Since Math.random() returns a double value, you can cast its result to int if you want to return integer values.

No comments:

Post a Comment