改变获得随机数的概率 [英] changing probability of getting a random number
本文介绍了改变获得随机数的概率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想生成一个0和3之间的随机数,我在代码中有以下内容:
I would like to generate a random number between 0 and 3 and I have the following in my code:
int random = rand() % 4;
这很好,但我想它大多数时间生成1,2和3 0只是偶尔。
This works fine but I would like it to generate 1, 2, and 3 most of the time and 0 only occasionally.
这是最好的方法是什么?解决这个问题的常用算法的名称是什么?
What is the best way to go about this? What are the names of common algorithms to address this problem?
推荐答案
假设你想要0,1,2,3有5%,20%,30%,45%的分布。
你可以这样做:
Here's one way. Suppose you want 0, 1, 2, 3 to have a distribution of 5%, 20%, 30%, 45%.
You could do it like this:
double val = (double)rand() / RAND_MAX;
int random;
if (val < 0.05) // 5%
random = 0;
else if (val < 0.25) // 5% + 20%
random = 1;
else if (val < 0.55) // 5% + 20% + 30%
random = 2;
else
random = 3;
当然,它不必使用浮点。我只是这样做,因为它更直观。
Of course it doesn't have to be done with floating-point. I just did it this way since it's more intuitive.
这篇关于改变获得随机数的概率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文