Generate random numbers uniformly over an entire range

后端 未结 17 2335
野性不改
野性不改 2020-11-22 04:21

I need to generate random numbers within a specified interval, [max;min].

Also, the random numbers should be uniformly distributed over the interval, not located to

17条回答
  •  心在旅途
    2020-11-22 05:13

    Why rand is a bad idea

    Most of the answers you got here make use of the rand function and the modulus operator. That method may not generate numbers uniformly (it depends on the range and the value of RAND_MAX), and is therefore discouraged.

    C++11 and generation over a range

    With C++11 multiple other options have risen. One of which fits your requirements, for generating a random number in a range, pretty nicely: std::uniform_int_distribution. Here's an example:

    const int range_from  = 0;
    const int range_to    = 10;
    std::random_device                  rand_dev;
    std::mt19937                        generator(rand_dev());
    std::uniform_int_distribution  distr(range_from, range_to);
    
    std::cout << distr(generator) << '\n';
    

    And here's the running example.

    Template function may help some:

    template
    T random(T range_from, T range_to) {
        std::random_device                  rand_dev;
        std::mt19937                        generator(rand_dev());
        std::uniform_int_distribution    distr(range_from, range_to);
        return distr(generator);
    }
    

    Other random generators

    The header offers innumerable other random number generators with different kind of distributions including Bernoulli, Poisson and normal.

    How can I shuffle a container?

    The standard provides std::shuffle, which can be used as follows:

    std::vector vec = {4, 8, 15, 16, 23, 42};
    
    std::random_device random_dev;
    std::mt19937       generator(random_dev());
    
    std::shuffle(vec.begin(), vec.end(), generator);
    

    The algorithm will reorder the elements randomly, with a linear complexity.

    Boost.Random

    Another alternative, in case you don't have access to a C++11+ compiler, is to use Boost.Random. Its interface is very similar to the C++11 one.

提交回复
热议问题