## Calculating Binomial Probabilities using C#

Suppose you flip a coin 10 times. What is the probability you’ll get exactly 2 heads? This is an example of a binomial probability problem. In math terms n is the number of trials (10 for the example), k is the number of “successes” (2), and p is the probability of getting a success in a single trial. Because heads and tails are equally likely, p = 0.5 in this example.

From Wikipedia, the equation for calculating Pr(k | n,p) is:

The trickiest part is calculating the Choose(n,k) function because Choose() can return astronomically large values for even moderate size of n and k. For example, Choose(500, 100) =

204,169,423,593,847,671,561,387,240,724,193,094,030,165,
460,090,325,932,474,143,661,505,758,330,944,415,515,994,
945,349,100,113,181,687,417,345

One solution is to use a BigInteger class that can handle arbitrarily large integers. (The alternative is to use the Normal approximation to the binomial).

So I put it all together in a C# program and validated my result using the R language which has a built-in pbinom() function.

Good mental exercise.