ProbStat.java


Below is the syntax highlighted version of ProbStat.java from §3.6 Case Study: Purple America.


/******************************************************************************
 *  Compilation:  javac ProbStat.java
 *  Execution:    java ProbStat
 *
 ******************************************************************************/

public class ProbStat {

    // gaussian pdf with mean mu and stddev sigma
    public static double gaussian(double mu, double sigma, double x) {
        double num =  Math.exp( - (x - mu) * (x - mu) / (2 * sigma * sigma) );
        double den = sigma * Math.sqrt(2 * Math.PI);
        return num / den;
    }

    // return log n!
    public static double logFact(int n) {
        double ans = 0.0;
        for (int i = 1; i <= n; i++)
            ans += Math.log(i);
        return ans;
    }

    // return the probability of getting exactly k heads when throwing N biased p coins
    public static double binomial(int N, double p, int k) {
        return Math.exp(logFact(N) - logFact(k) - logFact(N-k) + k*Math.log(p) + (N-k)*Math.log(1-p));
    }


}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 14:12:12 EDT 2017.