EN
Java - Math.random() method example
0 points
The Math.random()
function returns floating-point, pseudo-random number between range [0,1), 0 (inclusive) and 1 (exclusive). Based on this function we are able to get a random number in range as we can see in the below examples.
Simple usage example:
xxxxxxxxxx
1
public class MathExample {
2
3
static double randomDouble(double min,double max) {
4
return min + Math.floor((max - min) * Math.random());
5
}
6
7
static double randomFloat(float min, float max) {
8
return min + (max - min) * Math.random();
9
}
10
11
public static void main(String[] args) {
12
System.out.println( Math.random() ); // 0.9100486004606172
13
System.out.println( Math.random() ); // 0.8630710741089413
14
System.out.println( Math.random() ); // 0.8052253695967542
15
16
System.out.println( randomDouble( 10, 20) ); // 12.0
17
System.out.println( randomDouble(-10, 10) ); // -4.1
18
19
System.out.println( randomFloat( 10, 20) ); // 14.514897223860018
20
System.out.println( randomFloat(-10, 10) ); // -6.645075993092653
21
}
22
}
Syntax |
xxxxxxxxxx 1 package java.lang; 2 3 public final class Math { 4 5 public static double random() { ... } 6 7 }
|
Parameters | This method does not take any arguments. |
Result | double number value (primitive value). |
Description | random is a static method that returns random float number from therange <0, 1) - inclusive 0 and exclusive 1. |
This example shows how to random numbers.
xxxxxxxxxx
1
public class MathExample {
2
3
static double randomizeDouble(double min, double max) {
4
return min + (max - min) * Math.random();
5
}
6
7
public static void main(String[] args) {
8
System.out.println( randomizeDouble(-100.0, -10.0)); // -19.47848124694505
9
System.out.println( randomizeDouble( -8.0, 50.0 )); // 9.235851074094608
10
System.out.println( randomizeDouble(100.1, 1000.0)); // 292.6323795235495
11
}
12
}
xxxxxxxxxx
1
import java.util.Random;
2
3
public class MathExample {
4
5
static double randomizeDouble(double min, double max) {
6
Random rand = new Random();
7
8
return rand.nextDouble() * (max - min) + min;
9
}
10
11
public static void main(String[] args) {
12
System.out.println( randomizeDouble(-100.0, -10.0)); // -26.680584788543626
13
System.out.println( randomizeDouble( -8.0, 50.0 )); // 28.283331926707007
14
System.out.println( randomizeDouble(100.1, 1000.0)); // 464.69065618362106
15
}
16
}