Which approach is best at generating random numbers?

时间:2019-04-16 23:18:07

标签: c++

What kind of approach is the best at generating a random 2-digit number (using only the standard C++ library)? These 2 seem like the most obvious, but I want to know which one is better and if there is a better one.

//1
#include <iostream>
#include <cstdlib>
#include <ctime>
int main()
{
     std::srand(std::time(NULL));
     std::cout << "Random value: " << std::rand() % 100;
     return 0;
}

//2
#include <iostream>
#include <random>
int main()
{
     std::random_device rnd;
     std::cout << "Random value: " << rnd() % 100;
     return 0;
}

1 个答案:

答案 0 :(得分:4)

Neither of those is very good. You want a less predictable seed (which srand/rand can't do), and a uniform distribution (which % 100 of just about anything won't do).

Instead, use the C++11 standard <random> PRNG suite (adapted from cppreference example code):

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

    // Seed the default ending from good random
    std::default_random_engine eng(r());

    // Define a proper distribution that won't exhibit bias
    std::uniform_int_distribution<int> dist(0, 99);

    std::cout << "Random value: " << dist(eng) << std::endl;
}

Technically, the standard is a bit weak on std::random_device and allows it to be non-cryptographically random, but on all major OSes it should be decent. You're welcome to xor r() with time(NULL) if you want to ensure it's at least non-repeating, though it won't guarantee good randomness.