C# How to Generate Random Number Depends on Probab

2019-02-24 09:47发布

问题:

I have a situation in which I must generate a random number, this number must be either zero or one

So, the code is something like this:

randomNumber = new Random().Next(0,1)

However, the business requirements state that there is just 10% probability that the generated number is zero and 90% probability that the generated number is 1

However can I include that probability in generating the random number please?

What I thought of is:

  1. Generate array of integer that includes 10 zeros and 90 ones.
  2. Generate a random index between 1 and 100
  3. Take the value that corresponds to that index

But I don't know if this way is the correct way, plus, I think that C# should have something ready for it

回答1:

You can implement it like that:

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


回答2:

to get true with a probability of 10%:

bool result = new Random().Next(1, 11) % 10 == 0;

to get true with a probability of 40%:

bool result = new Random().Next(1, 11) > 6;


回答3:

First of all, you should save the reference to the random instance in order to get a proper random sequence of numbers:

Random randGen = new Random();

The second thing to know, is that the max of the random is exclusive, so to properly solve the issue you should do:

int eitherOneOrZero = randGen.Next(1, 11) % 10;

To generalize it to any variation of chances, you can do:

Random randGen = new Random();
var trueChance = 60;

int x = randGen.Next(0, 100) < trueChance ? 1 : 0;

Testing:

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++;
    }
}

Output:

True: 60.30 %

False: 39.70 %