I need to r otate each vertex ( x i , y i ) by degrees counterclockwise, around
ID: 3723078 • Letter: I
Question
I need to rotate each vertex (x i, y i) by degrees counterclockwise, around the origin.
Hint:
xiyi=xicosyisin=yicos+xisin
xi=xicosyisinyi=yicos+xisin
My code is
public static void rotate(double[] x, double[] y, double theta) {
for (int i = 0; i < x.length; i++) {
x[i] = Math.cos(Math.toRadians(theta)) * x[i]
- Math.sin(Math.toRadians(theta)) * y[i];
}
for (int i = 0; i < y.length; i++) {
y[i] = Math.cos(Math.toRadians(theta)) * y[i]
+ Math.sin(Math.toRadians(theta)) * x[i];
}
}
But it doesn't seem to work, particularly on the y.
Explanation / Answer
Here is the code which will solve your issue. The problem with your code was that you were updating the x[i] value in first for loop and then using the updated value in second for loop though you are supposed to use original value of x[i] while calculating new y[i].
public static void rotate(double[] x, double[] y, double theta) {
double xnew, ynew;
for (int i = 0; i < x.length; i++) {
xnew = Math.cos(Math.toRadians(theta)) * x[i]
- Math.sin(Math.toRadians(theta)) * y[i];
ynew = Math.cos(Math.toRadians(theta)) * y[i]
+ Math.sin(Math.toRadians(theta)) * x[i];
x[i] = xnew;
y[i] = ynew;
}
}