Computing hypergeometric probability efficiently in C++
Computing hypergeometric function is a slow and difficult process, often affected by overflow errors as evaluating binomial coefficient may return extremely large numbers. Fortunately, thanks to some hypergeometric identities, is possible to evaluate the hypergeometric probability quickly.
I’ve implemented and tested the HyperQuick algorithm, from;
Aleš Berkopec, HyperQuick algorithm for discrete hypergeometric distribution, Journal of Discrete Algorithms 5 (2007) 341–347
that evaluates the value of hypergeometric cumulative distribution of the form:
\[C(n,x,N,M) = \sum \limits_{j=0}^x \frac{\binom{M}{j}\binom{N-M}{n-j}}{\binom{N}{n}}\]The demonstration is based on the binomial identity
\[\sum \limits_{k=0}^x \binom{M}{k}\binom{N-M}{n-k} = \sum \limits_{m=M}^{N-n+x} \binom{m}{x}\binom{N-1-m}{N-m-n+x}\]As shown by the author, for any accuracy \(\epsilon \geq 0\) the required number of computational cycles is less then \(N-n\), where \(N\) is the size of the population and \(n\) is the size of the sample. Here I provide the straight C++ implementation of the pseudocode the author provides in its paper, for real-wolrd uses. Please let me know if you find any bug.
The code is pretty self-explanatory and any porting in languages like Python is straightforwardly implementable. A full implementation of Hyperquick is available at: