Facebook Page Twitter Page LinkedIn Page
× PHP Tutorial PHP Advanced PHP Resources


The PHP Math random() function returns a double value in range [0.0, 1.0). The returned value is chosen pseudo-randomly from uniform distribution (approximately) from that range.

To generate a random in different range, the random() can be used. For example-

  • To generate a random number in range [0.0, 10.0), the expression random()*10 can be used.
  • To generate a random number in range [-1.0, 1.0), the expression random()*2 - 1 can be used.

Syntax

//version 1
rand()

//version 2
rand(min, max)

Parameters

No parameter is required.

Return Value

Returns pseudo-random double in range [0.0, 1.0).

Example:

In the below example, random() function is used to generate a pseudo-random double in range [0.0, 1.0).

public class MyClass {
 public static void main(String[] args) {
  System.out.println(Math.random());   
  System.out.println(Math.random());
  System.out.println(Math.random());     
 }
}

The output of the above code will be:

0.2778296598497003
0.6421976830440985
0.18591614847496474

Example:

In the below example, the function is used to generate a pseudo-random double in range [0.0, 10.0).

public class MyClass {
 public static void main(String[] args) {
  System.out.println(Math.random()*10);   
  System.out.println(Math.random()*10);
  System.out.println(Math.random()*10);     
 }
}

The output of the above code will be:

3.925911027583192
4.588044289363738
3.115186794654875

Example:

In the same way, it can be used to generate a pseudo-random double in range [-1.0, 1.0).

public class MyClass {
 public static void main(String[] args) {
  System.out.println(Math.random()*2-1);   
  System.out.println(Math.random()*2-1);
  System.out.println(Math.random()*2-1);     
 }
}

The output of the above code will be:

0.616550701127146
0.5330712637034409
-0.9722965205765486

❮ PHP Math Functions