Random Numbers in Groovy
Our first example demonstrates how to generate random numbers in Groovy. Here’s the full source code:
import java.util.Random
class RandomNumbers {
static void main(String[] args) {
// Create a new Random object
def random = new Random()
// Generate random integers between 0 (inclusive) and 100 (exclusive)
print "${random.nextInt(100)},"
println random.nextInt(100)
// Generate a random float between 0.0 (inclusive) and 1.0 (exclusive)
println random.nextDouble()
// Generate random floats in the range 5.0 <= f < 10.0
print "${5 + random.nextDouble() * 5},"
println 5 + random.nextDouble() * 5
// If you want a known seed, create a new Random object with a specific seed
def seededRandom = new Random(42)
print "${seededRandom.nextInt(100)},"
println seededRandom.nextInt(100)
// Creating another Random object with the same seed will produce the same sequence
def seededRandom2 = new Random(42)
print "${seededRandom2.nextInt(100)},"
println seededRandom2.nextInt(100)
}
}
To run the program, save it as RandomNumbers.groovy
and use the groovy
command:
$ groovy RandomNumbers.groovy
68,56
0.8090228139659177
5.840125017402497,6.937056298890035
94,49
94,49
Some of the generated numbers may be different when you run the sample.
In this example:
We use the
java.util.Random
class to generate random numbers.random.nextInt(100)
generates a random integer between 0 (inclusive) and 100 (exclusive).random.nextDouble()
generates a random double between 0.0 (inclusive) and 1.0 (exclusive).We demonstrate how to generate random doubles in a specific range (5.0 to 10.0) by scaling and shifting the output of
nextDouble()
.We show how to create a
Random
object with a specific seed, which will always produce the same sequence of random numbers for a given seed.We create two
Random
objects with the same seed to demonstrate that they produce the same sequence of numbers.
Note that Groovy doesn’t have a direct equivalent to Go’s math/rand/v2
package or its PCG implementation. The Java Random
class uses a different algorithm (Linear Congruential Generator), but it serves a similar purpose for generating pseudorandom numbers.
For more advanced random number generation, you might want to look into the Apache Commons Math library, which provides additional random number generators and distributions.