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) =


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.


This entry was posted in Machine Learning. Bookmark the permalink.