Skip to main content

atan2

Function atan2 

Source
pub const fn atan2(y: Real, x: Real) -> Real
Expand description

Computes the four-quadrant arctangent of y / x (atan2(y, x)).

Returns the angle in radians between the positive x-axis and the point (x, y), in the range [-π, π]. This function correctly handles all special cases (including signed zeros, infinities, and NaNs) as required by IEEE 754-2008.

§Special cases

  • atan2(±0, ±0) returns ±0 or ±π according to the sign of x
  • atan2(±y, ±0) returns ±π/2
  • atan2(±y, ±∞) returns ±0 or ±π
  • atan2(±∞, ±x) returns ±π/2
  • atan2(±∞, ±∞) returns ±π/4 or ±3π/4
  • Any NaN argument produces NaN

§Implementation notes

This is a const fn-compatible port of the FreeBSD libm implementation (e_atan2.c). The original algorithm uses range reduction and calls to atan for the core computation, with careful handling of the PI_LO correction for negative x to ensure correct rounding.

Modifications for this crate:

  • Adapted to the generic Real type (which is f64 under the hood)
  • Made fully const fn compatible using method calls (.abs(), .is_nan()) instead of the fabs helper
  • Uses the const fn version of atan from super::atan
  • Removed no_panic attribute and any f64-specific hardcoding

§Testing

This function has been validated with a comprehensive test suite that includes:

  • Sanity checks across all four quadrants and axis angles
  • All IEEE 754 special values (NaN, signed zeros, infinities)
  • Extreme ratio cases (|y/x| > 2⁶⁴ and |y/x| < 2⁻⁶⁴)
  • Explicit verification of the PI_LO correction path
  • Fast-path for x == 1.0

All tests pass with bit-exact or correctly-rounded results matching the original libm implementation.