C++ 不同概率的随机数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12885356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Random numbers with different probabilities
提问by Josh Brittain
Possible Duplicate:
C++ function for picking from a list where each element has a distinct probability
I need to randomly determine a yes or no outcome (kind of a coin flip) based on a probability that I can define (.25, .50, .75).
我需要根据我可以定义的概率(0.25、0.50、0.75)随机确定是或否结果(类似于抛硬币)。
So for example, I want to randomly determine yes or no where yes has a 75% chance of being chosen. What are my options for this? Is there a C++ library I can use for this?
因此,例如,我想随机确定是或否,其中是有 75% 的机会被选中。我有什么选择?有没有我可以使用的 C++ 库?
回答by Luchian Grigore
You can easily implement this using the rand
function:
您可以使用以下rand
函数轻松实现这一点:
bool TrueFalse = (rand() % 100) < 75;
The rand() % 100
will give you a random number between 0 and 100, and the probability of it being under 75 is, well, 75%. You can substitute the 75
for any probability you want.
该rand() % 100
会给你0和100之间,它是在75的概率是随机数,以及75%。您可以将 替换75
为您想要的任何概率。
回答by 111111
Check at the C++11 pseudo random number library.
检查 C++11 伪随机数库。
http://en.cppreference.com/w/cpp/numeric/random
http://en.cppreference.com/w/cpp/numeric/random
http://en.wikipedia.org/wiki/C%2B%2B11#Extensible_random_number_facility
http://en.wikipedia.org/wiki/C%2B%2B11#Extensible_random_number_facility
std::random_device rd;
std::uniform_int_distribution<int> distribution(1, 100);
std::mt19937 engine(rd()); // Mersenne twister MT19937
int value=distribution(engine);
if(value > threshold) ...
like this, then say all above 75 is true, and all below is false, or whatever threshold you want
像这样,然后说 75 以上都是真的,以下都是假的,或者你想要的任何阈值
Unlike rand
you can actually control the properties of the number generation, also I don't believe rand as used in other answers (using modulo) even presents a uniform distribution, which is bad.
与rand
您可以实际控制数字生成的属性不同,我也不相信 rand 用于其他答案(使用模数)甚至呈现均匀分布,这很糟糕。
回答by BigBoss
std::random_device
or boost::random
if std::random_device
is not implemented by your C++ compiler, using a boost::random
you can use bernoulli_distribution
to generate a random bool
value!
std::random_device
或者boost::random
如果std::random_device
你的 C++ 编译器没有实现,使用一个boost::random
你可以bernoulli_distribution
用来生成一个随机bool
值!
回答by Ionut Hulub
#include <cstdlib>
#include <iostream>
using namespace std;
bool yesOrNo(float probabilityOfYes) {
return rand()%100 < (probabilityOfYes * 100);
}
int main() {
srand((unsigned)time(0));
cout<<yesOrNo(0.897);
}
if you call yesOrNo(0.75)
it will return true
75% of the time.
如果您调用yesOrNo(0.75)
它将返回true
75% 的时间。