BlueRay101
BlueRay101

Reputation: 1487

Percentage Based Probability

I have this code snippet:

Random rand = new Random();
int chance = rand.Next(1, 101);

if (chance <= 25) // probability of 25%
{
    Console.WriteLine("You win");
}
else
{
    Console.WriteLine("You lose");
}

My question is, does it really calculate a 25% probability for winning here? Is the chance of winning for the player here is really 25%?

Edit:

I just wrote this:

        double total = 0;
        double prob = 0;
        Random rnd = new Random();
        for (int i = 0; i < 100; i++)
        {
            double chance = rnd.Next(1, 101);
            if (chance <= 25) prob++;
            total++;
        }
        Console.WriteLine(prob / total);
        Console.ReadKey();

And it's highly inaccurate. It goes from about 0.15 to 0.3.

But when I do more checks (change from (i < 100) to (i < 10000)) it's much more accurate.

Why is this? Why aren't 100 checks enough for it to be accurate?

Upvotes: 16

Views: 26269

Answers (3)

Rotem
Rotem

Reputation: 21947

This is very easy to check for yourself:

Random rand = new Random(); 
int yes = 0;
const int iterations = 10000000;
for (int i = 0; i < iterations; i++)
{
   if (rand.Next(1, 101) <= 25)
   {
       yes++;
   }
}
Console.WriteLine((float)yes/iterations);

the result:

0.2497914

The conslusion: Yes, yes it is.


Edit: Just for fun, the LINQy version:

Random rand = new Random(); 
const int iterations = 10000000;
int sum = Enumerable.Range(1, iterations)
                    .Count(i => rand.Next(1, 101) <= 25);
Console.WriteLine(sum / (float)iterations);

Upvotes: 16

AwokeKnowing
AwokeKnowing

Reputation: 8246

yes, that should work fine. just as >=75 would work too. if you just want 25%, you can go ahead and just do a random number between 1 and 4.

but please note, a 25% chance does NOT mean that out of 100 tries, he will win 25 times. It just means each time he has a 25% chance of winning. it's theoretically possible for him to win every single time. (but that will not happen, especially with a pseudo-random generator).

Internally the random number will be between 0 and 1 so it's just as random to use 4 as 1000, as far as that goes. add the parameter just projects it to the range you want.

Upvotes: 1

Gerald T
Gerald T

Reputation: 25

For most cases, I would say yes. However, you have to remember that most randomization algorithms use a pseudo-random generator, and so to some extent, you're at the mercy of the idiosyncrasies of that particular generator. I do agree with @AwokeKnowing that you can you also just do a random number between 1 and 4 and get the same result. I assume that the .Net randomization algorithm should suffice for most cases. For more info see:

http://en.wikipedia.org/wiki/Pseudorandom_number_generator

Upvotes: 1

Related Questions