FunctionGraph.java

Below is the syntax highlighted version of FunctionGraph.java from §1.5 Input and Output. 




/*************************************************************************
 *  Compilation:  javac FunctionGraph.java 
 *  Execution:    java FunctionGraph
 *  Dependencies: StdDraw.java
 *
 *  Plots the function y = sin(4x) + sin(20x) between x = 0 and x = pi
 *  by drawing N line segments.
 *
 *************************************************************************/

public class FunctionGraph {
    public static void main(String[] args) {

        // number of line segments to plot
        int N = Integer.parseInt(args[0]);

        // the function y = sin(4x) + sin(20x), sampled at N points
        // between x = 0 and x = pi
        double[] a = new double[N+1];
        for (int i = 0; i <= N; i++) {
            a[i] = Math.sin(4*Math.PI*i/N) + Math.sin(20*Math.PI*i/N);
        }

        // rescale the coordinate system
        StdDraw.setXscale(0, N);
        StdDraw.setYscale(-2.0, +2.0);

        // plot the approximation to the function
        for (int i = 0; i < N; i++) {
            StdDraw.line(i, a[i], i+1, a[i+1]);
        }
    }
}




Copyright © 2007, Robert Sedgewick and Kevin Wayne. 
Last updated: Sun May 13 18:22:27 EDT 2007.