Scala Tutorial Scala References

Scala - Math random() Method



The Scala Math random() method 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

def random(): Double = java.lang.Math.random()

Parameters

No parameter is required.

Return Value

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

Exception

NA.

Example:

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

object MainObject {
  def main(args: Array[String]) {
    println(Math.random()); 
    println(Math.random());
    println(Math.random());
  }
}

The output of the above code will be:

0.5275595446423137
0.5047183027083707
0.8745864957286094

Example:

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

object MainObject {
  def main(args: Array[String]) {
    println(Math.random()*10); 
    println(Math.random()*10);
    println(Math.random()*10);
  }
}

The output of the above code will be:

2.774524163603309
1.5606091750148676
9.080488282053311

Example:

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

object MainObject {
  def main(args: Array[String]) {
    println(Math.random()*2-1); 
    println(Math.random()*2-1);
    println(Math.random()*2-1);
  }
}

The output of the above code will be:

0.9156801780904309
-0.5050279423455823
0.44643270722776296

❮ Scala - Math Methods