C#如何生成随机数取决于概率

Mar*_*oli 4 .net c# random math distributed-computing

我有一种情况,我必须生成一个随机数,这个数字必须是zeroone

所以,代码是这样的:

randomNumber = new Random().Next(0,1)
Run Code Online (Sandbox Code Playgroud)

但是,业务要求表明生成的数字为零的可能性仅为10%,生成的数字为1的概率为90%

但是,我可以在生成随机数时包括这个概率吗?

我想到的是:

  1. 生成包含10个零和90个整数的整数数组.
  2. 生成1到100之间的随机索引
  3. 获取与该索引对应的值

但是我不知道这种方式是否正确,而且,我认为C#应该为它做好准备

fub*_*ubo 5

以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)


Dmi*_*nko 5

你可以像这样实现它:

  // 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)