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:
public class MathExample {
static double randomDouble(double min,double max) {
return min + Math.floor((max - min) * Math.random());
}
static double randomFloat(float min, float max) {
return min + (max - min) * Math.random();
}
public static void main(String[] args) {
System.out.println( Math.random() ); // 0.9100486004606172
System.out.println( Math.random() ); // 0.8630710741089413
System.out.println( Math.random() ); // 0.8052253695967542
System.out.println( randomDouble( 10, 20) ); // 12.0
System.out.println( randomDouble(-10, 10) ); // -4.1
System.out.println( randomFloat( 10, 20) ); // 14.514897223860018
System.out.println( randomFloat(-10, 10) ); // -6.645075993092653
}
}
1. Documentation
Syntax |
|
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. |
2. Custom random method examples
2.1. Random double in range example
This example shows how to random numbers.
public class MathExample {
static double randomizeDouble(double min, double max) {
return min + (max - min) * Math.random();
}
public static void main(String[] args) {
System.out.println( randomizeDouble(-100.0, -10.0)); // -19.47848124694505
System.out.println( randomizeDouble( -8.0, 50.0 )); // 9.235851074094608
System.out.println( randomizeDouble(100.1, 1000.0)); // 292.6323795235495
}
}
2.2 With nextDouble() method
import java.util.Random;
public class MathExample {
static double randomizeDouble(double min, double max) {
Random rand = new Random();
return rand.nextDouble() * (max - min) + min;
}
public static void main(String[] args) {
System.out.println( randomizeDouble(-100.0, -10.0)); // -26.680584788543626
System.out.println( randomizeDouble( -8.0, 50.0 )); // 28.283331926707007
System.out.println( randomizeDouble(100.1, 1000.0)); // 464.69065618362106
}
}