Mar*_*oli 4 .net c# random math distributed-computing
我有一种情况,我必须生成一个随机数,这个数字必须是zero或one
所以,代码是这样的:
randomNumber = new Random().Next(0,1)
Run Code Online (Sandbox Code Playgroud)
但是,业务要求表明生成的数字为零的可能性仅为10%,生成的数字为1的概率为90%
但是,我可以在生成随机数时包括这个概率吗?
但是我不知道这种方式是否正确,而且,我认为C#应该为它做好准备
以10%的概率获得真实:
bool result = new Random().Next(1, 11) % 10 == 0;
Run Code Online (Sandbox Code Playgroud)
以40%的概率获得真实:
bool result = new Random().Next(1, 11) > 6;
Run Code Online (Sandbox Code Playgroud)
你可以像这样实现它:
// 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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1208 次 |
| 最近记录: |