Groovy Operators

Control Statements

Groovy File Handling

Groovy Error & Exceptions

Groovy Multithreading

Groovy Synchronization

Groovy - random() method



The random() method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math.random < 1.0. Different ranges can be achieved by using arithmetic.

Syntax

static double random()

Parameters

NA

Return Value

This method returns a randome double between 0.0 and 1.0.

Example - Usage of random() method to generate random numbers.

Following is an example of the usage of this method −

Example.groovy

class Example {     
   static void main(String[] args){	
      println( Math.random() );
      println( Math.random() );
   } 
}

Output

When we run the above program, we will get the following result −

0.541596758314524
0.8943580021189237

Example - Usage of random() method to generate random numbers between 0 and 10.

Following is an example of the usage of this method −

Example.groovy

class Example {     
   static void main(String[] args){	
      println( 10 * Math.random() );
      println( 10 * Math.random() );
   } 
}

Output

When we run the above program, we will get the following result −

6.783693988502972
9.234223980409443

Example - Usage of random() method to generate random numbers between -10 and 0.

Following is an example of the usage of this method −

Example.groovy

class Example {     
   static void main(String[] args){	
      println( -10 * Math.random() );
      println( -10 * Math.random() );
   } 
}

Output

When we run the above program, we will get the following result −

-6.925204404397963
-4.591727275570449
groovy_numbers.htm
Advertisements