The ATAN2() function in SQLite calculates the arc tangent (inverse tangent) of the ratio of two given numeric values, typically representing the y-coordinate and x-coordinate of a point.
Unlike ATAN(), which calculates the angle based only on a single tangent value, ATAN2() considers both the x and y values to determine the correct quadrant for the resulting angle.
Syntax
ATAN2(Y, X)
Y: The y-coordinate (or opposite side length in trigonometric terms).X: The x-coordinate (or adjacent side length in trigonometric terms).
The result will be an angle in radians between -π and π, allowing for a complete angle measurement around a circle (from -180° to 180°). This accounts for the direction and quadrant, as both coordinates are considered.
Difference Between ATAN() and ATAN2()
ATAN(X)calculates the arc tangent of a single value, providing an angle in radians between -π/2 and π/2 (i.e., from -90° to 90°). It does not distinguish between points in different quadrants, so it only gives the angle based on the tangent’s absolute value.ATAN2(Y, X), however, uses bothYandXto identify the correct quadrant of the angle, returning a more complete range of angles (-π to π) based on the coordinates. This is particularly useful for 2D coordinate systems, where knowing the quadrant is essential.
Example 1
Here’s a quick example to demonstrate how it works:
SELECT ATAN2(5, 7);
Output:
0.620249485982821
Example 2
Suppose we have a table points with columns x and y that represent coordinates on a 2D plane. We want to calculate the angle between each point and the positive x-axis.
CREATE TABLE points (x REAL, y REAL);
INSERT INTO points (x, y) VALUES (1, 1), (-1, 1), (-1, -1), (1, -1), (0, 1);
Now, we can use ATAN2() to calculate the angle for each point:
SELECT x, y, ATAN2(y, x) AS angle_in_radians
FROM points;
Output:
x y angle_in_radians
---- ---- ------------------
1.0 1.0 0.785398163397448
-1.0 1.0 2.35619449019234
-1.0 -1.0 -2.35619449019234
1.0 -1.0 -0.785398163397448
0.0 1.0 1.5707963267949
In this example:
- For the point
(1, 1),ATAN2(1, 1)returns0.785398163397448radians (π/4), which is in the first quadrant. - For
(-1, 1),ATAN2(1, -1)returns approximately2.35619449019234radians (3π/4), indicating the second quadrant. - For
(-1, -1),ATAN2(-1, -1)returns approximately-2.35619449019234radians, indicating the third quadrant. - For
(1, -1),ATAN2(-1, 1)returns approximately-0.785398163397448radians, indicating the fourth quadrant. - For
(0, 1),ATAN2(1, 0)returns1.5707963267949radians (π/2), which is directly on the positive y-axis.
The ATAN2() function is essential in applications like computer graphics, physics, and navigation, where calculating the angle of a vector in a 2D space requires precise quadrant-based angles.