Random Numbers in Cilk

The cilk library provides functionality for generating random numbers. Here’s an example of how to use it:

#include <cilk/cilk.h>
#include <cilk/cilkscreen.h>
#include <iostream>
#include <random>
#include <chrono>

int main() {
    // Create a random number generator
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::default_random_engine generator(seed);

    // Generate random integers between 0 and 99
    std::uniform_int_distribution<int> int_distribution(0, 99);
    std::cout << int_distribution(generator) << "," << int_distribution(generator) << std::endl;

    // Generate random float between 0.0 and 1.0
    std::uniform_real_distribution<double> real_distribution(0.0, 1.0);
    std::cout << real_distribution(generator) << std::endl;

    // Generate random floats between 5.0 and 10.0
    std::uniform_real_distribution<double> range_distribution(5.0, 10.0);
    std::cout << range_distribution(generator) << "," << range_distribution(generator) << std::endl;

    // Use a known seed for reproducible results
    std::default_random_engine seeded_generator(42);
    std::cout << int_distribution(seeded_generator) << "," << int_distribution(seeded_generator) << std::endl;

    // Using the same seed produces the same sequence
    std::default_random_engine seeded_generator2(42);
    std::cout << int_distribution(seeded_generator2) << "," << int_distribution(seeded_generator2) << std::endl;

    return 0;
}

In this example, we use C++’s random number generation facilities, which are part of the standard library. Cilk itself doesn’t provide specific random number generation functions, but it can be used with C++’s standard library.

Here’s a breakdown of what the code does:

  1. We create a random number generator using the current time as a seed.

  2. We use std::uniform_int_distribution to generate random integers between 0 and 99.

  3. std::uniform_real_distribution is used to generate random floating-point numbers between 0.0 and 1.0.

  4. We demonstrate how to generate random floats in a specific range (5.0 to 10.0).

  5. We show how to use a known seed (42 in this case) to create a reproducible sequence of random numbers.

  6. Finally, we demonstrate that using the same seed produces the same sequence of random numbers.

To compile and run this program:

$ cilk++ random_numbers.cpp -o random_numbers
$ ./random_numbers
68,56
0.809023
5.84013,6.93706
94,49
94,49

Note that the actual numbers generated will likely be different when you run the program, except for the last two lines which use a fixed seed.

The C++ random number generation facilities provide a wide range of distributions and engines. For more advanced use cases, you might want to explore other distributions like std::normal_distribution, std::poisson_distribution, etc., or other random engines like std::mt19937.