Table of Contents

math.atan2()

Function Definition: math.atan2(y, x)

Parameters

NameTypeDescriptionExpected ValuesDefault Value
yfloatRequired. Specifies a positive or negative numbernumber
xfloatRequired. Specifies a positive or negative numbernumber

Description

Math is key in programming and in Python there is a powerful library dedicated to performing math functions – the Math Library. One of the functions in this library is the math.atan2() function. It takes two arguments and spits out an angle in radians in a range of -pi to pi. In this tutorial, we will explore how to use the Python math.atan2() function.

Definition

The math.atan2() function in Python takes two arguments – y-coordinate and x-coordinate – and produces an angle in radians from -(pi) to +(pi). It is similar to the functionality of the math.atan() function, although it is more capable of handling more complex angles.

Usecase

You may want to compute angles in Python and math.atan2() comes in handy for the purpose. One example could be cartography, where one needs to know the angle of a line joining two points on a map.

Examples with Output

Let us understand the math.atan2() function with some examples.

Example 1

Let us try to compute the angle between the two points (3, 8) and (7, 6).

import math

# let's compute the angle between the two points p1(3, 8) and p2 (7, 6). 
a = atan2(6-8,7-3)  

# printing the angle 
print("The angle between two points is",a)

Output: The angle between two points is -0.7853981633974483

Example 2

Let us now try to compute the angle between the two points (7, 2) and (12, 8).

import math

# let's compute the angle between the two points p1(7,2) and p2 (12,8). 
b = atan2(8-2, 12-7) 

# printing the angles 
print("The angle between two points is",b) 

Output: The angle between two points is 1.2490457723982544

Conclusion

In conclusion, we learned what math.atan2() is and how to use it. We saw two examples with code output that explained how to compute angles between two points using Python math.atan2() function. Now it’s time to practice to solidify your understanding!

Example

There are no examples documented for this article.