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:

  1. We use the Random module which provides pseudorandom number generation capabilities.

  2. We create a RandomStream object to generate random numbers. By default, it uses a different seed each time the program is run.

  3. To generate random integers between 0 and 99, we multiply the random float by 100 and cast it to an integer.

  4. rng.getNext() returns a random real number between 0.0 and 1.0.

  5. We can generate random numbers in other ranges by scaling and shifting the output of getNext().

  6. To get reproducible results, we can create a RandomStream with a known seed.

  7. 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:

$ chpl random_numbers.chpl -o random_numbers
$ ./random_numbers
68,56
0.809022813965918
5.84012501740249,6.93705629889004
94,49
94,49

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.