Alan Kaminsky Department of Computer Science Rochester Institute of Technology 4486 + 2220 = 6706
Home Page

Simulation Simplified
4. Chi-Square Test
Class Dice07

import edu.rit.numeric.BernoulliPrng;
import edu.rit.numeric.Statistics;
import edu.rit.numeric.plot.Plot;
import edu.rit.numeric.plot.Strokes;
import edu.rit.util.Random;
public class Dice07
   {
   public static void main
      (String[] args)
      throws Exception
      {
      if (args.length != 3) usage();
      int maxwin = Integer.parseInt (args[0]);
      int N = Integer.parseInt (args[1]);
      long seed = Long.parseLong (args[2]);
      BernoulliPrng prng =
         new BernoulliPrng (Random.getInstance (seed), 5.0/6.0);
      double[] actual = new double [maxwin + 1];
      for (int trial = 0; trial < N; ++ trial)
         {
         int win = 0;
         do
            {
            ++ win;
            }
         while (prng.next());
         actual[Math.min (win - 1, maxwin)] += 1;
         }
      double[] winamount = new double [maxwin + 1];
      for (int i = 0; i <= maxwin; ++ i) winamount[i] = i + 1;
      double[] expected = new double [maxwin + 1];
      double sum_p_i = 0.0;
      System.out.printf ("Win\tActual\tExpected%n");
      for (int i = 0; i < maxwin; ++ i)
         {
         double p_i = Math.pow (5.0/6.0, i)/6.0;
         sum_p_i += p_i;
         expected[i] = N*p_i;
         System.out.printf ("%.0f\t%.0f\t%.3f%n",
            winamount[i], actual[i], expected[i]);
         }
      expected[maxwin] = N*(1.0 - sum_p_i);
      System.out.printf ("%.0f\t%.0f\t%.3f%n",
         winamount[maxwin], actual[maxwin], expected[maxwin]);
      double chisqr = Statistics.chiSquareTest (actual, expected);
      double pvalue = Statistics.chiSquarePvalue (maxwin, chisqr);
      System.out.printf ("Chi^2   = %.6f%n", chisqr);
      System.out.printf ("P-value = %.6f%n", pvalue);
      new Plot()
         .plotTitle ("Dice Game")
         .xAxisTitle ("Winnings")
         .yAxisTitle ("Occurrences")
         .seriesStroke (null)
         .xySeries (winamount, actual)
         .seriesDots (null)
         .seriesStroke (Strokes.solid (1))
         .xySeries (winamount, expected)
         .getFrame()
         .setVisible (true);
      }

   private static void usage()
      {
      System.err.println
         ("Usage: java Dice07 <maxwin> <N> <seed>");
      System.exit (1);
      }
   }
Alan Kaminsky Department of Computer Science Rochester Institute of Technology 4486 + 2220 = 6706
Home Page
Copyright © 2011 Alan Kaminsky. All rights reserved. Last updated 31-Aug-2011. Please send comments to ark­@­cs.rit.edu.