1

I'm looking for an efficient Java implementation of Binomial coefficients ( choose(n,k) ) defined for all real numbers n and integers k, ie defined as:

enter image description here

talonmies
  • 70,661
  • 34
  • 192
  • 269
fbielejec
  • 3,492
  • 4
  • 27
  • 35
  • Check out the [Wikipedia entry] (http://en.wikipedia.org/wiki/Binomial_coefficient) – user949300 Dec 02 '11 at 03:05
  • All "real numbers `n`". I hope you realize that implies emitting the [Gamma Function](http://en.wikipedia.org/wiki/Gamma_function). – Mysticial Feb 27 '12 at 06:33
  • @Mystical, the denominator 'k' is integer, thus there is no gamma implied. Even though it's efficient unless 'k' is small. For small 'k' it may be more efficient to simply iterate the few multiplications and divisions, alternating, starting from the lower end to keep the error low... – Susanne Oberhauser Nov 05 '13 at 19:40

1 Answers1

2

With usage of Apache Commons Math 3:

import org.apache.commons.math3.special.Gamma;

/**
 * Binomial coefficient for real numbers - the number of ways of picking y
 * unordered outcomes from x possibilities
 *
 * @see http://mathworld.wolfram.com/BinomialCoefficient.html
 *
 * @param x
 * @param y
 * @return binomial coefficient to be generalized to noninteger arguments
 */
public double binomial(double x, double y) {
    double res = Gamma.gamma(x + 1) / (Gamma.gamma(y + 1) * Gamma.gamma(x - y + 1));
    if(Double.isNaN(res)){
        return 0.0;
    }
    return res;
}

So for input binomial(0.5, 1.0) you should get 0.5, like in Wolfram Alpha

binomial(2.5, 3) = 0.3125
binomial(2.0, 3) = 0.0
binomial(1.5, 3) = -0.0625
Tombart
  • 30,520
  • 16
  • 123
  • 136