INTRODUCTION TO COMPUTER SCIENCE
Robert Sedgewick and Kevin Wayne


This is the syntax highlighted version of Sampling.java.


/*************************************************************************
 *  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 = MyMath.Phi( (0.5*N - p*N) / Math.sqrt(N*p*(1-p)) );
      System.out.println("probability = " + prob);
   }

}


Last updated: Wed Feb 11 18:07:23 EST 2004 .
Copyright © 2004, Robert Sedgewick and Kevin Wayne.