在C ++中生成一个统一的随机整数 [英] Generating a uniform random integer in C++
问题描述
问题是我需要生成一个0到999之间的随机整数(用于研究数学猜想).所有这些值都必须具有相同的上升概率.
The problem is that I need to generate a random integer between 0 and 999 (for investigation of a mathematical conjecture). All of the values need to have the same probability of coming up.
我尝试了rand()
,但是RAND_MAX
为32767(在我的编译器上),这意味着仅采用rand() % 1000
会导致出现第一个1–767的可能性大大提高(并且假设所有可能性首先在rand()
中具有相同的概率.
I have tried rand()
, but with RAND_MAX
being 32767 (on my compiler) this means that just taking rand() % 1000
leads to the first 1–767 being significantly more likely to come up (and that's assuming that all possibilities have the same probability in rand()
in the first place).
我使用的是Windows,所以/dev/random
不能选择.
I'm using Windows so /dev/random
isn't an option.
推荐答案
您可以使用 uniform_int_distribution
与C ++ 11:
You can do something like this using uniform_int_distribution
with C++11:
#include <iostream>
#include <random>
int main()
{
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> dis(0, 999);
for (int n=0; n<1000; ++n)
std::cout << dis(gen) << ' ';
std::cout << '\n';
}
这篇关于在C ++中生成一个统一的随机整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!