Skip to content

C rand() is not a great RNG #4

@jeffhammond

Description

@jeffhammond

If PRNG quality or performance matters at all, you will be happier with https://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution than this:

Also, push_back is a slow way to populate a vector. Reserve the space in the constructor and then fill it in one shot. If you do it with a loop, use x[i] after reserving all the space.

   // primal solution vector (random guess on [-0.001:0.001])
    srand(0);
    std::vector<double> x;
    for (size_t i = 0; i < n_primal_; i++) {
        x.push_back(2.0 * ( (double)rand()/RAND_MAX - 1.0 ) * 0.001);
    }

I think this works...

    #include <random>
    #include <algorithm>
    #include <iterator>
    ...
    // primal solution vector (random guess on [-0.001:0.001])
    std::random_device r;
    std::mt19937 m{r()};
    std::uniform_real_distribution<double> d{-0.001,0.001};
    std::vector<double> x(n_primal_);
    std::generate(x.begin(), x.end(),  [&]() { return d(m); });

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions