Skip to main content

wrap_pm_pi

Function wrap_pm_pi 

Source
pub fn wrap_pm_pi(x: f64) -> f64
Expand description

Wraps an angle to [-pi, +pi) radians.

Use for quantities where the discontinuity should be at +/-180 degrees (the “back” of the circle), not at 0/360 degrees.

§Arguments

  • x - Angle in radians (any value, including negative or > 2pi)

§Returns

The equivalent angle in [-pi, +pi).

§When to Use

  • Hour angle: hours from meridian, negative = east, positive = west
  • Longitude differences: shortest arc between two longitudes
  • Galactic/ecliptic longitude: if you want galactic center at l=0
  • Position angle differences: relative rotation between two frames

§Examples

use celestial_core::angle::wrap_pm_pi;
use std::f64::consts::PI;

// 270 degrees -> -90 degrees
let x = wrap_pm_pi(3.0 * PI / 2.0);
assert!((x - (-PI / 2.0)).abs() < 1e-10);

// -270 degrees -> +90 degrees
let y = wrap_pm_pi(-3.0 * PI / 2.0);
assert!((y - (PI / 2.0)).abs() < 1e-10);

// Already in range: unchanged
let z = wrap_pm_pi(1.0);
assert!((z - 1.0).abs() < 1e-10);

§Algorithm

  1. Reduce to [-2pi, +2pi) via fmod(x, 2pi)
  2. If result is >= pi or <= -pi, subtract/add 2pi to bring into range