
// FunctionGraph.java
// Robert Sedgewick and Kevin Wayne
// Slightly reformatted by Andrew Davison, Nov. 2022

// https://introcs.cs.princeton.edu/java/33design/FunctionGraph.java.html

/* Plot the function y = sin(4x) + sin(20x) between x = 0 and x = pi
   by drawing n line segments.

   Usage:
     > compile FunctionGraph.java
     > run FunctionGraph <no. of lines>
   e.g.
     > run FunctionGraph 600
*/

public class FunctionGraph
{
  public static void main(String[] args)
  {
    if (args.length != 1) {
      System.out.println("Usage: run FunctionGraph <no. of lines; e.g. 600>");
      return;
    }
    int n = Integer.parseInt(args[0]);

    // the function y = sin(4x) + sin(20x), sampled at n+1 points
    // between x = 0 and x = pi
    double[] x = new double[n+1];
    double[] y = new double[n+1];
    for (int i = 0; i <= n; i++) {
      x[i] = Math.PI * i / n;
      y[i] = Math.sin(4*x[i]) + Math.sin(20*x[i]);
    }

    // rescale the coordinate system
    StdDraw.setXscale(0, Math.PI);
    StdDraw.setYscale(-2.1, +2.1);

    // plot the approximation to the function
    for (int i = 0; i < n; i++)
      StdDraw.line(x[i], y[i], x[i+1], y[i+1]);
  } /* main */


}  // end of FunctionGraph class
