C#如何生成随机数取决于概率
我有一种情况,我必须生成一个随机数,这个数字必须是zero
或one
所以,代码是这样的:
randomNumber = new Random().Next(0,1)
但是,业务要求表明生成的数字为零的概率仅为10%,生成的数字为1的概率为90%
但是,我可以在生成随机数时包括这个概率吗?
我的想法是:
- 生成包含10个零和90个整数的整数数组。
- 生成1到100之间的随机索引
- 获取与该索引对应的值
但我不知道这种方式是否正确,而且,我认为C#应该为它准备好一些东西
你可以像这样实现它:
// Do not re-create Random! Create it once only // The simplest implementation - not thread-save private static Random s_Generator = new Random(); ... // you can easiliy update the margin if you want, say, 91.234% const double margin = 90.0 / 100.0; int result = s_Generator.NextDouble() <= margin ? 1 : 0;
以10%的概率获得真实:
bool result = new Random().Next(1, 11) % 10 == 0;
以40%的概率获得真实:
bool result = new Random().Next(1, 11) > 6;
首先,您应该保存对随机实例的引用,以便获得正确的随机数字序列:
Random randGen = new Random();
第二件事是,随机的最大值是独占的,所以要正确解决你应该做的问题:
int eitherOneOrZero = randGen.Next(1, 11) % 10;
要将其概括为任何机会变化,您可以:
Random randGen = new Random(); var trueChance = 60; int x = randGen.Next(0, 100) < trueChance ? 1 : 0;
测试:
Random randGen = new Random(); var trueChance = 60; var totalCount = 1000; var trueCount = 0; var falseCount = 0; for (int i = 0; i < totalCount; i++) { int x = randGen.Next(0, 100) < trueChance ? 1 : 0; if (x == 1) { trueCount++; } else { falseCount++; } }
输出:
真:60.30%
错误:39.70%