0

I'm using the turtle api to finish [this assignment] (http://sites.asmsa.org/java-turtle/exer/5-function-graphing). I'm stuck on graphing the cosine function displaying a user-specified number of periods. The for loop is what I'm using to generate the y-coordinates of the graph for intervals of x values. Wouldn't y = (x/2pi*period)? This is displaying too many periods though. (also amp is for amplitude, and I named my turtle don for donatello)

Scanner sc = new Scanner(System.in);
System.out.println("Enter the following values.");
System.out.print("Amplitude: ");
int amp = sc.nextInt();
System.out.print("Number of Periods:");
int per = sc.nextInt();
don.setPosition(-320, amp * Math.cos( -320 / (4 * Math.PI * per)));
don.down();
for(int x = -320; x < 320; x+=5) {
    double y = amp * Math.cos(x/(2 * Math.PI * per));
    don.setPosition(x, y);
}
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • You want to map the range (-320,320) to the range (0,2pi*per). So, you need `(x+320) * 2 * Math.PI * per / 640`. – Tim Roberts Jan 19 '22 at 21:19

1 Answers1

0

As a general rule, any time you want to map a range of M to a range of N, the formula is x * N / M. So, if x is 0, you get 0; if x in M, you get N.

You want to map the range (-320,320) to the range (0,2pi*per). So, you need (x+320) * 2 * Math.PI * per / 640.

Tim Roberts
  • 48,973
  • 4
  • 21
  • 30