Answered by:
Adding 3 numbers mystery in for loop
Question

Hello!
I have a mystery problem. The goal with this loop is to get the average number as close to 100 as possible but I always get the number around 106.75 more or less exactly.
I use a loop and Random.
 With 43% chance I add the number 43
 With 35% chance I add the number 35
 With 22% chance I add the number 22
I do 1 million(1000000) iterations to get a good average which should be as I am thinking:
43 + 35 + 22 = 100
But I do get 106.75. I am not sure why this is happening?
double total = 0; for (int i = 0; i < 1000000; i++) { double sum1 = 0; for (int t = 0; t < 3; t++) { randnum = rand.Next(0, 100000); double sum2 = 0; if (randnum >= 0 && randnum < 43000) { sum2 = 43; } //43% chance to add 43 if (randnum >= 43000 && randnum < 78000) { sum2 = 35; } //35% chance to add 35 if (randnum >= 78000 && randnum <= 100000) { sum2 = 22; } //22% chance to add 22 sum1 = sum1 + sum2; } total = total + sum1; } total = total / 1000000; MessageBox.Show(total.ToString());
 Edited by Silvers11 Thursday, November 29, 2018 11:09 PM
Answers

Greetings Silvers.
If you want an average of 100, that means you want 43, 35, and 22 to be chosen an equal number of times. That means those three numbers need to have an equal probability of being randomly chosen, not a biased probability.
for (int t = 0; t < 3; t++) { randnum = rand.Next(0, 100000); double sum2 = 0; if (randnum >= 1 && randnum <= 33333) { sum2 = 43; } else if (randnum > 33333 && randnum <= 66666) { sum2 = 35; } else if (randnum > 66666 && randnum <= 100000) { sum2 = 22; } sum1 = sum1 + sum2; }
 Marked as answer by Silvers11 Thursday, November 29, 2018 11:29 PM
All replies

Greetings Silvers.
If you want an average of 100, that means you want 43, 35, and 22 to be chosen an equal number of times. That means those three numbers need to have an equal probability of being randomly chosen, not a biased probability.
for (int t = 0; t < 3; t++) { randnum = rand.Next(0, 100000); double sum2 = 0; if (randnum >= 1 && randnum <= 33333) { sum2 = 43; } else if (randnum > 33333 && randnum <= 66666) { sum2 = 35; } else if (randnum > 66666 && randnum <= 100000) { sum2 = 22; } sum1 = sum1 + sum2; }
 Marked as answer by Silvers11 Thursday, November 29, 2018 11:29 PM

