Java Binomial Coefficients binomialCoefficient(double n, double k)

Here you can find the source of binomialCoefficient(double n, double k)

Description

binomial Coefficient

License

Open Source License

Declaration

public static double binomialCoefficient(double n, double k) 

Method Source Code

//package com.java2s;
/*//  w ww.jav  a  2s  . c o  m
 * Copyright 2007 Luis Rodero Merino.  All Rights Reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Luis Rodero Merino if you need additional information or
 * have any questions. Contact information:
 * Email: lrodero AT gsyc.es
 * Webpage: http://gsyc.es/~lrodero
 * Phone: +34 91 488 8107; Fax: +34 91 +34 91 664 7494
 * Postal address: Desp. 121, Departamental II,
 *                 Universidad Rey Juan Carlos
 *                 C/Tulip?n s/n, 28933, M?stoles, Spain 
 *       
 */

public class Main {
    private static double[] FACTORIALS = { 1.0, 2.0, 6.0, 24.0 };

    public static double binomialCoefficient(double n, double k) {
        return factorial(n) / (factorial(k) * factorial(n - k));
    }

    public static double factorial(double n) {

        if (n < 0.0)
            throw new Error("Can not compute the factorial of a negative number");

        if (n <= 1.0)
            return 1.0;

        if (n <= 4.0) {
            int floor = (int) Math.floor(n);
            int ceil = (int) Math.ceil(n);
            if (floor == ceil)
                return FACTORIALS[floor - 1];
            return ((n - floor) * (FACTORIALS[ceil - 1] - FACTORIALS[floor - 1]) / (ceil - floor)) + floor;
        }

        // Stirling 
        double fact = Math.sqrt(2 * Math.PI * n) * Math.pow(n / Math.E, n);

        return fact;
    }
}

Related

  1. binomial(int n, final int k)
  2. binomial(int N, int K)
  3. binomial(int n, int k)
  4. binomialCdf(int k, int n, double p)
  5. binomialCoeff(int n, int k)
  6. binomialCoefficient(int n, int k)
  7. binomialCoefficient(int n, int k)
  8. binomialCoefficient(int n, int k)
  9. binomialCoefficient(long n, long k)