SawTooth.java


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


/******************************************************************************
 *  Compilation:  javac SawTooth.java
 *  Execution:    java SawTooth n
 *  
 *  Plots an approximation to a sawtooth wave via Fourier analysis.
 *
 ******************************************************************************/


public class SawTooth { 
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        StdDraw.setCanvasSize(1400, 500);
        StdDraw.setXscale(0, 6 * Math.PI);
        StdDraw.setYscale(-2, 2);
        StdDraw.enableDoubleBuffering();

        double xprev = 0.0;

        for (double t = 0.0; t <= 6*Math.PI; t += 0.005) {
            double x = 0.0;
            for (int k = 1; k <= n; k++) {
                x += Math.sin(k*t) / k;
            }
            x = x * 2 / Math.PI;
            StdDraw.line(t - 0.005, xprev, t, x);
            xprev = x;
        }
        StdDraw.show();

    }
}


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