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:

atan2($y, $x)

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 π-\pi to π\pi (or -180° to 180°), depending on the signs of $y and $x.

Example 1: Basic Usage of atan2()

<?php $y = 1; // y-coordinate $x = 1; // x-coordinate // Calculate angle using atan2 $angle = atan2($y, $x); echo $angle; // Outputs in radians ?>

Output:

0.78539816339745

In this example, the angle is approximately π4\frac{\pi}{4} 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.

<?php $y = 1; // y-coordinate $x = 1; // x-coordinate // Calculate angle using atan2 $angle_radians = atan2($y, $x); // Convert to degrees $angle_degrees = rad2deg($angle); echo "Angle in degrees: " . $angle_degrees; ?>

Output:

Angle in degrees: 45

Example 3: Handling Different Quadrants

The atan2() function correctly identifies the angle based on the signs of both $y and $x.

<?php // Different combinations of y and x $coordinates = [ [1, 1], // Quadrant I [1, -1], // Quadrant II [-1, -1], // Quadrant III [-1, 1] // Quadrant IV ]; foreach ($coordinates as $coord) { $y = $coord[0]; $x = $coord[1]; $angle = atan2($y, $x); echo "Coordinates ($x, $y): Angle in radians: $angle, Angle in degrees: " . rad2deg($angle) . "\n"; } ?>

Output:

Coordinates (1, 1): Angle in radians: 0.78539816339745, Angle in degrees: 45 Coordinates (-1, 1): Angle in radians: 2.3561944901923, Angle in degrees: 135 Coordinates (-1, -1): Angle in radians: -3.9269908169873, Angle in degrees: -225 Coordinates (1, -1): Angle in radians: -0.78539816339745, Angle in degrees: -45

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 π-\pi to π\pi 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.