Java Binomial Coefficients binomialPmf(int k, int n, double p)

Here you can find the source of binomialPmf(int k, int n, double p)

Description

binomial Pmf

License

Open Source License

Declaration

public static double binomialPmf(int k, int n, double p) 

Method Source Code

//package com.java2s;
// it under the terms of the GNU General Public License as published by      //

public class Main {
    private static final double[] cof = { 76.18009172947146,
            -86.50532032941677, 24.01409824083091, -1.231739572450155,
            0.1208650973866179e-2, -0.5395239384953e-5 };

    public static double binomialPmf(int k, int n, double p) {

        if (p == 0.0) {
            return ((k == 0) ? 1.0 : 0.0);
        } else if (p == 1.0) {
            return ((k == n) ? 1.0 : 0.0);
        } else if ((k < 0) || (k > n)) {
            return 0.0;
        } else {//  ww w .j  a  v  a 2  s  .  c  o  m
            return (Math.exp(lngamma(n + 1.0) - lngamma(k + 1.0)
                    - lngamma(n - k + 1.0) + k * Math.log(p) + (n - k)
                    * Math.log(1.0 - p)));
        }
    }

    /**
     * This is a more literal (that is, exact) copy of the log gamma method from
     * Numerical Recipes than the following one.  It was created by cutting and
     * pasting from the PDF version of the book and then converting C syntax to
     * Java. </p> The static double array above goes with this. </p> Converted
     * to Java by Frank Wimberly
     *
     * @return the value ln[?(xx)] for xx > 0
     */
    public static double lngamma(double xx) {
        //Returns the value ln[?(xx)] for xx > 0.

        if (xx <= 0)
            return Double.NaN;

        //Internal arithmetic will be done in double precision, a nicety that you can omit if ?ve-?gure
        //accuracy is good enough.
        double x, y, tmp, ser;

        int j;
        y = x = xx;
        tmp = x + 5.5;
        tmp -= (x + 0.5) * Math.log(tmp);
        ser = 1.000000000190015;
        for (j = 0; j <= 5; j++) {
            ser += cof[j] / ++y;
        }
        return -tmp + Math.log(2.5066282746310005 * ser / x);
    }
}

Related

  1. binomialCoefficient(int n, int k)
  2. binomialCoefficient(long n, long k)
  3. binomialCoefficientDouble(final int n, final int k)
  4. binomialCoefficientLog(final int n, final int k)
  5. binomialCoefficients(int n, int k)
  6. binomialRand(int n, double pp)