Sampling.java


Below is the syntax highlighted version of Sampling.java from §2.1 Static Methods.


/******************************************************************************
 *  Compilation:  javac Sampling.java
 *  Execution:    java Sampling n p
 *
 *  Suppose that p = 40% of the population favors candidate A. If we take a
 *  random sample of n = 200 voters, what is the probability that less than
 *  half the voters support candidate A?
 *
 *  The number X of the n = 200 voters that support candidate A is binomial
 *  distributed with mean n * p = 200 * 0.4 = 50 and variance
 *  n * p * (1 - p) = 200 * 0.4 * 0.6 = 48. The standard deviation is
 *  The probability that less than half the voters support candidate A is
 *  the probability that X < n / 2 = 100.
 *
 *  Using the normal approximation to the binomial distribution, the
 *  probability that X < 100 is:
 *     P(Z <= (100-80) / sqrt(48)) = P (Z <= 2.886)
 *
 *
 ******************************************************************************/

public class Sampling {

    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        double p = Double.parseDouble(args[1]);

        double prob = Gaussian.Phi((0.5*n - p*n) / Math.sqrt(n*p*(1-p)));
        StdOut.println("probability = " + prob);
    }

}


Copyright © 2000–2022, Robert Sedgewick and Kevin Wayne.
Last updated: Thu Aug 11 10:15:13 EDT 2022.