binomial Coefficient - Java java.lang

Java examples for java.lang:Math Function

Description

binomial Coefficient

Demo Code

/*// w w w . j  a v a2  s . co 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 
 *       
 */
//package com.java2s;

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 Tutorials