Python 3 – Number atan2() Method
In Python 3, arithmetic operations like trigonometry are essential. The atan2() function is one such method that computes the arc tangent of y/x in radians. The method takes two arguments, y and x, as input and returns the result in radians. Python treats the result as NaN (Not-a-Number) when both the inputs are zero.
Syntax:
The syntax of the atan2() function is as follows:
math.atan2(y, x)
Example 1 – Basic Usage
import math
y = 4
x = 4
result = math.atan2(y, x)
print('The result is: ', result)
Output:
The result is: 0.7853981633974483
Example 2 – Handling Special Cases
Let’s say when both inputs to the atan2 method is zero, it must return NaN values. This is because the output of atan2 is undefined when both x and y are zero.
import math
x = 0
y = 0
atan_result = math.atan2(y, x)
print(f"The result is {atan_result}")
Output:
The result is nan
We use {value}
format to concatenate the string and the result.
Example 3 – Using atan2 with coordinate geometry
An important application of atan2() is in determining the angle of rotation of an object in space. For instance, if a point P is present on Cartesian space, and we want to find the angle between the point and x-axis, we make use of the atan2() function.
Here’s an example to illustrate the use of atan2() with coordinate geometry.
import math
x = 4
y = 4
angle = math.atan2(y, x)
print(f"The angle is {math.degrees(angle)}")
Output:
The angle is 45.0
We use the math.degrees
function to convert the value to degrees.
Example 4 – Calculation with Negative Numbers
Let’s say when we are calculating angles with negative numbers (quadrant 2 and 3 in the coordinate plane), the atan2 function works correctly.
import math
x = -4
y = -4
angle = math.atan2(y, x)
print(f"The angle is {math.degrees(angle)}")
Output:
The angle is -135.0
Conclusion
In this article, we learned the basics of the atan2() function in Python. We also illustrated various use-cases of the method, such as handling special cases where both input parameters are zero, calculating angle of rotation of an object in space, and calculating with negative numbers. By using the atan2() method, you can write more efficient and accurate programs with better trigonometric functions.