Random Numbers in Chapel
Chapel provides a module called Random
for generating pseudorandom numbers. Let’s explore how to use it.
In this Chapel program:
We use the
Random
module which provides pseudorandom number generation capabilities.We create a
RandomStream
object 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 randomreal
number 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
RandomStream
with a known seed.Two
RandomStream
objects 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:
Note 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.