Calculate the angle between the straight line and the horizontal axis
Determining the angle between a straight line and a horizontal axis is a common need in various programming scenarios. Given two points (P1x,P1y) and (P2x,P2y), the goal is to calculate this angle.
First, we need to determine the incremental value (difference) between the end point and the starting point:
<code>deltaY = P2_y - P1_y deltaX = P2_x - P1_x</code>
Next, we can calculate the angle using the arctangent function (arctan) and convert the result from radians to degrees:
<code>angleInDegrees = arctan(deltaY / deltaX) * 180 / PI</code>
Alternatively, if your programming language provides the atan2 function, use it in preference to handling quadrant problems:
<code>angleInDegrees = atan2(deltaY, deltaX) * 180 / PI</code>
Depending on specific requirements, you may need to adjust to account for the quadrant the angle is in. By considering the sign of deltaX and deltaY you can determine the appropriate quadrant and adjust the angle accordingly.
Python sample code
The following Python code demonstrates the implementation of the above method:
<code class="language-python">from math import * def getAngleBetweenPoints(x_orig, y_orig, x_landmark, y_landmark): deltaY = y_landmark - y_orig deltaX = x_landmark - x_orig return degrees(atan2(deltaY, deltaX)) # 使用degrees函数直接转换为角度 angle = getAngleBetweenPoints(5, 2, 1, 4) assert angle >= 0, "angle must be >= 0" angle = getAngleBetweenPoints(1, 1, 2, 1) assert angle == 0, "expecting angle to be 0" angle = getAngleBetweenPoints(2, 1, 1, 1) assert abs(180 - angle) < 1e-6, "expecting angle to be 180" # 使用更精确的断言 </code>
This code contains additional checks to ensure accuracy in calculating angles. We used the degrees
function to directly convert radians to degrees, simplifying the code. And the last assertion is judged more accurately to avoid errors in floating point comparison.
The above is the detailed content of How to Calculate the Angle Between Two Points and the Horizontal Axis?. For more information, please follow other related articles on the PHP Chinese website!