MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / rotate

Function rotate

graphics/vector3_for_2d_rendering.py:38–94  ·  view source on GitHub ↗

rotate a point around a certain axis with a certain angle angle can be any integer between 1, 360 and axis can be any one of 'x', 'y', 'z' >>> rotate(1.0, 2.0, 3.0, 'y', 90.0) (3.130524675073759, 2.0, 0.4470070007889556) >>> rotate(1, 2, 3, "z", 180) (0.999736015495891

(
    x: float, y: float, z: float, axis: str, angle: float
)

Source from the content-addressed store, hash-verified

36
37
38def rotate(
39 x: float, y: float, z: float, axis: str, angle: float
40) -> tuple[float, float, float]:
41 """
42 rotate a point around a certain axis with a certain angle
43 angle can be any integer between 1, 360 and axis can be any one of
44 'x', 'y', 'z'
45
46 >>> rotate(1.0, 2.0, 3.0, 'y', 90.0)
47 (3.130524675073759, 2.0, 0.4470070007889556)
48
49 >>> rotate(1, 2, 3, "z", 180)
50 (0.999736015495891, -2.0001319704760485, 3)
51
52 >>> rotate('1', 2, 3, "z", 90.0) # '1' is str
53 Traceback (most recent call last):
54 ...
55 TypeError: Input values except axis must either be float or int: ['1', 2, 3, 90.0]
56
57 >>> rotate(1, 2, 3, "n", 90) # 'n' is not a valid axis
58 Traceback (most recent call last):
59 ...
60 ValueError: not a valid axis, choose one of 'x', 'y', 'z'
61
62 >>> rotate(1, 2, 3, "x", -90)
63 (1, -2.5049096187183877, -2.5933429780983657)
64
65 >>> rotate(1, 2, 3, "x", 450) # 450 wrap around to 90
66 (1, 3.5776792428178217, -0.44744970165427644)
67 """
68 if not isinstance(axis, str):
69 raise TypeError("Axis must be a str")
70 input_variables = locals()
71 del input_variables["axis"]
72 if not all(isinstance(val, (float, int)) for val in input_variables.values()):
73 msg = (
74 "Input values except axis must either be float or int: "
75 f"{list(input_variables.values())}"
76 )
77 raise TypeError(msg)
78 angle = (angle % 360) / 450 * 180 / math.pi
79 if axis == "z":
80 new_x = x * math.cos(angle) - y * math.sin(angle)
81 new_y = y * math.cos(angle) + x * math.sin(angle)
82 new_z = z
83 elif axis == "x":
84 new_y = y * math.cos(angle) - z * math.sin(angle)
85 new_z = z * math.cos(angle) + y * math.sin(angle)
86 new_x = x
87 elif axis == "y":
88 new_x = x * math.cos(angle) - z * math.sin(angle)
89 new_z = z * math.cos(angle) + x * math.sin(angle)
90 new_y = y
91 else:
92 raise ValueError("not a valid axis, choose one of 'x', 'y', 'z'")
93
94 return new_x, new_y, new_z
95

Callers 1

Calls

no outgoing calls

Tested by

no test coverage detected