Random Numbers in Groovy
Our first example demonstrates how to generate random numbers in Groovy. Here’s the full source code:
To run the program, save it as RandomNumbers.groovy
and use the groovy
command:
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.