Random Numbers in Chapel
Chapel provides a module called Random for generating pseudorandom numbers. Let’s explore how to use it.
use Random;
proc main() {
// Create a random stream
var rng = new RandomStream(real);
// Generate a random integer between 0 and 99 (inclusive)
writef("%i,", (rng.getNext() * 100):int);
writef("%i\n", (rng.getNext() * 100):int);
// Generate a random float between 0.0 and 1.0
writeln(rng.getNext());
// Generate random floats in the range 5.0 <= f < 10.0
writef("%r,", rng.getNext() * 5 + 5);
writef("%r\n", rng.getNext() * 5 + 5);
// Create a new random stream with a known seed
var seededRng = new RandomStream(real, seed=42);
writef("%i,", (seededRng.getNext() * 100):int);
writef("%i\n", (seededRng.getNext() * 100):int);
// Create another stream with the same seed
var seededRng2 = new RandomStream(real, seed=42);
writef("%i,", (seededRng2.getNext() * 100):int);
writef("%i\n", (seededRng2.getNext() * 100):int);
}In this Chapel program:
We use the
Randommodule which provides pseudorandom number generation capabilities.We create a
RandomStreamobject to generate random numbers. By default, it uses a different seed each time the program is run.To generate random integers between 0 and 99, we multiply the random float by 100 and cast it to an integer.
rng.getNext()returns a randomrealnumber between 0.0 and 1.0.We can generate random numbers in other ranges by scaling and shifting the output of
getNext().To get reproducible results, we can create a
RandomStreamwith a known seed.Two
RandomStreamobjects created with the same seed will produce the same sequence of random numbers.
To run the program, save it as random_numbers.chpl and use the Chapel compiler:
$ chpl random_numbers.chpl -o random_numbers
$ ./random_numbers
68,56
0.809022813965918
5.84012501740249,6.93705629889004
94,49
94,49Note that the actual numbers generated may be different when you run the sample, except for the seeded random streams which should produce the same results each time.
For more information on random number generation in Chapel, refer to the Random module documentation in the Chapel language specification.