HI WELCOME TO SIRIS

c# probability and random numbers

Leave a Comment

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: 

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

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.