Search code examples
javabinomial-coefficients

Binomial coefficient for real values


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


Solution

  • 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