PHP atan2() function
The atan2()
function in PHP is used to calculate the arctangent of the quotient of two specified numbers (y/x), providing the angle (in radians) from the x-axis to the point (x, y) in a Cartesian coordinate system. Unlike the atan()
function, which only takes a single argument, atan2()
takes two arguments: the y-coordinate and the x-coordinate. This allows it to determine the correct quadrant of the angle, making it more robust for use in geometric calculations.
Syntax:
Parameters:
- $y: The y-coordinate of the point.
- $x: The x-coordinate of the point.
Return Value:
- The function returns the angle in radians, which ranges from to (or -180° to 180°), depending on the signs of $y and $x.
Example 1: Basic Usage of atan2()
Output:
In this example, the angle is approximately radians (or 45 degrees).
Example 2: Converting the Result to Degrees
You can convert the radians returned by atan2()
to degrees using the rad2deg()
function.
Output:
Example 3: Handling Different Quadrants
The atan2()
function correctly identifies the angle based on the signs of both $y and $x.
Output:
Practical Usage:
- The
atan2()
function is commonly used in graphics programming, robotics, and physics to compute angles based on Cartesian coordinates. - It is particularly useful for determining the direction of a vector in 2D space, allowing you to calculate angles for rotations or movements.
Summary:
atan2($y, $x)
computes the arctangent of the quotient of two coordinates, providing a complete angle in the range of to radians.- It correctly identifies the angle based on the signs of both $y and $x, making it more robust than the
atan()
function. - To convert from radians to degrees, use the
rad2deg()
function.