简体   繁体   中英

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:

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

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

minValue: The inclusive lower bound of the random number returned.

maxValue: The exclusive upper bound of the random number returned. maxValue must be greater than or equal to 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.

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. You should therefore use this:

if (random.Next(0, 100) < 25)

or, if you must use 1-based logic,

if (random.Next(1, 101) <= 25)

You can also use this code (usually for percentage calculations double between 0 and 1 is used):

double rand = random.NextDouble();
if(rand < .25)
{
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM