Lesson 12 of 15

Rotation

Rotation

Rotation matrices use sine and cosine to rotate points around the x, y, and z axes. C++ provides cos and sin from <cmath>, and the constant M_PI for π.

Rotation Around the Y Axis

rotation_y(θ) = [cos θ   0  sin θ  0]
                [0       1  0      0]
                [-sin θ  0  cos θ  0]
                [0       0  0      1]
Matrix4 rotation_y(double radians) {
    double c = cos(radians);
    double s = sin(radians);
    return Matrix4(c,0,s,0, 0,1,0,0, -s,0,c,0, 0,0,0,1);
}

Similarly for x and z axes:

Matrix4 rotation_x(double radians) {
    double c = cos(radians);
    double s = sin(radians);
    return Matrix4(1,0,0,0, 0,c,-s,0, 0,s,c,0, 0,0,0,1);
}

Matrix4 rotation_z(double radians) {
    double c = cos(radians);
    double s = sin(radians);
    return Matrix4(c,-s,0,0, s,c,0,0, 0,0,1,0, 0,0,0,1);
}

Floating-Point Precision

Due to floating-point arithmetic, cos(π/2) is not exactly 0. Use this helper to round small values:

double round5(double x) {
    return floor(x * 100000.0 + 0.5) / 100000.0;
}

Your Task

Implement rotation_y(double radians). Then rotate point(0, 0, 1) by π/2 radians (90°).

Expected result: point(1, 0, 0)

Expected output:

1 0 0
JSCPP loading...
Loading...
Click "Run" to execute your code.