PlotMean.java


Below is the syntax highlighted version of PlotMean.java.


/*******************************************************************************
 *  Name:    T. Shy
 *  Login:   jsshy
 *  Precept: P00
 *
 *  Compilation:  javac PlotMean.java
 *  Execution:    java PlotMean N
 *  Dependencies: StdDraw.java
 *
 *  Plots for N random doubles in the range [0., 1.) and their running average.  
 *  N is the first command-line argument.
 *
 ******************************************************************************/

public class PlotMean 
{
    public static void main(String[] args) {
        int N = Integer.parseInt(args[0]);
        double[] a = new double[N];

        //initialize "a" to random double values
        for (int i = 0; i < N; i++) {
            a[i] = Math.random();
        }

        StdDraw.setXscale(0, N-1);
	if (N > 0) StdDraw.setPenRadius(0.5/N);

        double sum = 0.0;
        double mean = 0.0;
        for (int i = 0; i < N; i++) {
            sum += a[i];
            mean = sum/(i + 1);

            StdDraw.setPenColor(StdDraw.BLACK);
            StdDraw.point(i, a[i]);

            //plot the running mean of the values seen so far
            StdDraw.setPenColor(StdDraw.RED);
            StdDraw.point(i, mean);
        }
    }
}