Home > Mobile >  How to change the iterative frequency in the following class
How to change the iterative frequency in the following class

Time:12-19

I used the following package

https://introcs.cs.princeton.edu/java/15inout/FunctionGraph.java.html

Thecode goes like this

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 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]);
        }
    }
}

I want to change the iterative interval to 0.1.

followed the following link for processing which is similar in syntax to java.

https://forum.processing.org/two/discussion/19180/plot-graph.html

tried this type of syntax using the float

float y; 
 for (float x=-maxX; x < maxX; x =.01) {

but its throwing an error showing declaration not possible in double. How to fix it.

Here is what i had done so far.


        // the function y = sin(4x)   sin(20x), sampled at N points
        // between x = 0 and x = pi
        float x ;
        float y ;
        for (float i = 0; i <= N; i =0.1) {
            x = Math.PI * i / n;; // 10 grid points per second
            y=Math.sin(4*x[i])   Math.sin(20*x[i]);;
        }

        // 
    }

CodePudding user response:

Instead of using float in the for loop, I would use int but increase the increments as below.

  public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        double[] x = new double[n 1];
        double[] y = new double[n 1];
        
        double t = 0.0;
        for (int i = 0; i <= n; i  ) {
            x[i] = Math.PI * t / n ;
            y[i] = Math.sin(4*x[i])   Math.sin(20*x[i]);
            System.out.printf(".4f.4f.4f\n", t, x[i], y[i]);
            t =0.1;
        }
  }

Would output the following for n = 10

java Main 10
0.0000    0.0000    0.0000
0.1000    0.0314    0.7131
0.2000    0.0628    1.1997
0.3000    0.0942    1.3192
0.4000    0.1257    1.0695
0.5000    0.1571    0.5878
0.6000    0.1885    0.0968
0.7000    0.2199   -0.1805
0.8000    0.2513   -0.1067
0.9000    0.2827    0.3170
1.0000    0.3142    0.9511
  •  Tags:  
  • java
  • Related