BLOG.CSHARPHELPER.COM: Calculate the probability of an event occurring in a given number of trials in C#
Calculate the probability of an event occurring in a given number of trials in C#
The post Understand probabilities of unrelated events (and escaping zombies) explains how to calculate the probability of an event occurring in a certain number of trials. It explains that if an event has a probability P of occurring at each trial, then after N trials the probability that at least one trial resulted in the event is 1 - (1 - P)N.
This example uses the following code to list probabilities of an event after certain numbers of trials.
// Calculate and display probabilities.
private void btnGo_Click(object sender, EventArgs e)
{
// See if the probability contains a % sign.
bool percent = txtEventProb.Text.Contains("%");
// Get the event probability.
double event_prob = double.Parse(txtEventProb.Text.Replace("%", ""));
// If we're using percents, divide by 100.
if (percent) event_prob /= 100.0;
// Get the probability of the event not happening.
double non_prob = 1.0 - event_prob;
lvwResults.Items.Clear();
for (int i = 0; i <= 100; i++)
{
double prob = 1.0 - Math.Pow(non_prob, i);
ListViewItem new_item = lvwResults.Items.Add(i.ToString());
if (percent)
{
prob *= 100.0;
new_item.SubItems.Add(prob.ToString("0.0000") + "%");
}
else
{
new_item.SubItems.Add(prob.ToString("0.000000"));
}
}
}
The code first determines whether the probability entered by the user contains the % symbol. If it does, then the program displays its output as a percentage. Otherwise it assumes the probabilities are as decimals values less than 1.
The code then parses the probability entered by the user and converts it into a value less than if it is a percentage.
The code subtracts the probability from 1 to get the probability of the event not occurring, and then enters a loop. For i = 0 to 100 the program calculates 1 minus the probability of the event not occurring to the ith power, converts the resul into a percentage if necessary, and displays the result in a ListView.
If you look closely at the picture, you'll see that the probability of a 1% event occurring after 100 trials is about 63%.
Comments