[英]c# probability and random numbers
I've seen this question asked in a number of ways, but I just need a sanity check of what I'm doing here.我已经看到这个问题以多种方式提出,但我只需要对我在这里所做的事情进行健全性检查。
Basically I want to trigger an event with a probability of 25% based on a random number generated between 1 and 100 using:基本上我想根据 1 到 100 之间生成的随机数触发一个概率为 25% 的事件:
int rand = random.Next(1,100);
Will the following achieve this?下面会实现这个吗?
if (rand<=25)
{
// Some event...
}
I thought I would use a number between 1 and 100 so I can tweak the probabilities later on - eg adjust to 23% by using我想我会使用 1 到 100 之间的数字,这样我可以稍后调整概率 - 例如通过使用调整到 23%
if (rand<=23) {...}
Thanks for taking a look.谢谢参观。
The biggest error you are making is it should be random.Next(0,100)
as the documentation states你犯的最大错误是它应该是random.Next(0,100)
正如文档所述
minValue: The inclusive lower bound of the random number returned. minValue:返回的随机数的下限。
maxValue: The exclusive upper bound of the random number returned. maxValue:返回的随机数的唯一上限。 maxValue must be greater than or equal to minValue. maxValue 必须大于或等于 minValue。
Emphisis mine, exclusive means it does not include number you passed in, so my code generates the range 0-99 and your code generates the range 1-99.强调我的,独占意味着它不包括你传入的数字,所以我的代码生成范围 0-99 而你的代码生成范围 1-99。
So change your code to所以将您的代码更改为
int rand = random.Next(0,100)
if (rand < 25) //25%
{
// Some event...
}
//other code
if (rand < 23) //23%
{
// Some event...
}
The change from <=
to <
is because you are now using the exclusive upper bounds range从<=
到<
的变化是因为您现在使用的是独占上限范围
The second argument of Next(int, int)
is the exclusive upper bound of the desired range of results. Next(int, int)
的第二个参数是所需结果范围的唯一上限。 You should therefore use this:因此你应该使用这个:
if (random.Next(0, 100) < 25)
or, if you must use 1-based logic,或者,如果您必须使用基于 1 的逻辑,
if (random.Next(1, 101) <= 25)
You can also use this code (usually for percentage calculations double between 0 and 1 is used):您也可以使用此代码(通常用于百分比计算,使用 0 和 1 之间的双精度值):
double rand = random.NextDouble();
if(rand < .25)
{
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.