Wednesday, 20 April 2016

C++11 Examples: Random Unsigned Integer Sequence

This is just a quick note, of using the C++11 random functions, to generate a positive list of random integers.

#include <iostream>
#include <string>
#include <random>
#include <cmath>

int main()
{
    // Seed with a real random value, if available
    std::random_device r;

    // Choose a random mean between 1 and 6
    std::default_random_engine e1(r());
    std::uniform_int_distribution<int> uniform_dist(1, 6);
    int mean = uniform_dist(e1);
    std::cout << "Randomly-chosen mean: " << mean << '\n';

    // Generate a normal distribution around that mean
    std::seed_seq seed2{r(), r(), r(), r(), r(), r(), r(), r()};
    std::mt19937 e2(seed2);
    std::normal_distribution<> normal_dist(20, 1000);
     

    // Loop edited by Xelous
    for (int n = 0; n < 10000; ++n)
    {
        unsigned int l_x = std::abs(normal_dist(e2));       
        std::cout << l_x << std::endl;
    }   
}


If you alter the uniform_dist spread to a higher yield, e.g. 1, 1000.  Then you increase the randomness of the mean used to generate the sequential seed.

This is taken straight from: http://en.cppreference.com/w/cpp/numeric/random

But, has been run on Coliru.

No comments:

Post a Comment