Logout

Random() & Other Math Methods

The Math class has many methods that are quite useful as well as a couple of attributes, such as pi.

Math.random() returns a random double value between the value of 0 and 1.

for(int i = 0; i < 5; i++){
            double d = Math.random();  // To modify the random result, * for range, and + for lowest possible value.
            System.out.println(d);
        }

Output:

0.21541693227585523
0.8370032094695297
0.04961280000543267
0.6974198718016187
0.6181542225034988
0.07715284169593639

 

So to get random values within a certain range, you take the returned value and multiply it by a the desired range.

Example 2:

        for(int i = 0; i < 5; i++){
            double d = Math.random()*50;  //Will yield a range of between 0 and 50.
            System.out.println(d);
        }

Output:

48.441899480101355
27.193049064301917
29.13334063190814
14.76680948138262
40.62663805043583

And to get random values within a certain range, but not with the lower limit zero, you add the value of the desired lower limit. This way the lowest possible value will be 0 + that value.

 

Example 3:

        for(int i = 0; i < 5; i++){
            double d = Math.random()*50 + 250;  //Will yield a range of between 250 and 300..
            System.out.println(d);
        }

Output:

290.1487931141402
290.343345808682
254.3397463720433
283.1585876272772
256.79850497076154

 

If we wanted random whole numbers, we would have to use casting, as explained above.

Example 4:

        for(int i = 0; i < 5; i++){
            double r1 = Math.random() * 60 + 40;
            long r2 = Math.round(r1);
            System.out.println(r2);
        }


Output:

88
92
97
96
61

 

For other Math methods, just take a look at the list that comes up when you type Math.___ The purpose of most familiar ones will be self evident to you. Just note that some will take more than one parameter.

For example

Math.pow(3,6) will return 3 to the power of 6, or 729.