diff --git a/compute.py b/compute.py index 976853d..9a9f470 100644 --- a/compute.py +++ b/compute.py @@ -116,6 +116,37 @@ def project_perspective( return (x * focal_length / depth * scale, y * focal_length / depth * scale) +def rot_3D(angle: float, axis: str) -> list[list[float]]: + """Gibt die 3D-Rotationsmatrix für eine Drehung um eine Koordinatenachse zurück. + + Rotation um die x-Achse: + [[1, 0, 0], [0, cos(a), -sin(a)], [0, sin(a), cos(a)]] + Rotation um die y-Achse: + [[cos(a), 0, sin(a)], [0, 1, 0], [-sin(a), 0, cos(a)]] + Rotation um die z-Achse: + [[cos(a), -sin(a), 0], [sin(a), cos(a), 0], [0, 0, 1]] + + Args: + angle: Drehwinkel a im Bogenmaß. + axis: Drehachse, "x", "y" oder "z". + + Returns: + Die 3x3-Rotationsmatrix als verschachtelte Liste. + + Raises: + ValueError: Wenn axis nicht "x", "y" oder "z" ist. + """ + cos_a = math.cos(angle) + sin_a = math.sin(angle) + if axis == "x": + return [[1, 0, 0], [0, cos_a, -sin_a], [0, sin_a, cos_a]] + if axis == "y": + return [[cos_a, 0, sin_a], [0, 1, 0], [-sin_a, 0, cos_a]] + if axis == "z": + return [[cos_a, -sin_a, 0], [sin_a, cos_a, 0], [0, 0, 1]] + raise ValueError("axis muss 'x', 'y' oder 'z' sein") + + if __name__ == "__main__": matrix_a = [ [3, 4, -1, 4], diff --git a/test/test_matrixmania/test_rot.py b/test/test_matrixmania/test_rot.py new file mode 100644 index 0000000..5ed6bb2 --- /dev/null +++ b/test/test_matrixmania/test_rot.py @@ -0,0 +1,65 @@ +import math + +import pytest + +from compute import rot_2D, rot_3D + + +def flatten(matrix: list[list[float]]) -> list[float]: + return [value for row in matrix for value in row] + + +def test_rot_2d_zero_angle_is_identity(): + # Arrange + angle = 0.0 + expected = [[1.0, 0.0], [0.0, 1.0]] + + # Act + result = rot_2D(angle) + + # Assert + assert flatten(result) == pytest.approx(flatten(expected)) + + +def test_rot_2d_quarter_turn(): + # Arrange + angle = math.pi / 2 + expected = [[0.0, -1.0], [1.0, 0.0]] + + # Act + result = rot_2D(angle) + + # Assert + assert flatten(result) == pytest.approx(flatten(expected), abs=1e-9) + + +def test_rot_3d_x_axis_quarter_turn(): + # Arrange + angle = math.pi / 2 + expected = [[1.0, 0.0, 0.0], [0.0, 0.0, -1.0], [0.0, 1.0, 0.0]] + + # Act + result = rot_3D(angle, "x") + + # Assert + assert flatten(result) == pytest.approx(flatten(expected), abs=1e-9) + + +def test_rot_3d_z_axis_zero_angle_is_identity(): + # Arrange + expected = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]] + + # Act + result = rot_3D(0.0, "z") + + # Assert + assert flatten(result) == pytest.approx(flatten(expected)) + + +def test_rot_3d_invalid_axis_raises_value_error(): + # Arrange + invalid_axis = "w" + + # Act / Assert + with pytest.raises(ValueError): + rot_3D(1.0, invalid_axis)