Skip to main content

embedded_maths/embedded-maths-functions/
atan.rs

1// SPDX-License-Identifier: GPL-2.0-or-later
2//! Arc tangent of `f32` for `no_std`, without `libm`.
3//!
4//! # Méthode
5//!
6//! Soit `a = |x|`. On réduit l'argument à `|t| <= tan(π/8)` :
7//!
8//! * `a > tan(3π/8)` : `atan(a) = π/2 + atan(-1/a)`
9//! * `a > tan(π/8)`  : `atan(a) = π/4 + atan((a-1)/(a+1))`
10//! * sinon           : `atan(a) = atan(a)`
11//!
12//! puis `atan(t) ≈ t + t·z·Q(z)`, avec `z = t²` et `Q` un polynôme minimax
13//! de degré 3 en `z` (coefficients de l'`atanf` de la bibliothèque Cephes,
14//! S. L. Moshier). Le signe de `x` est réappliqué sur le résultat.
15//!
16//! La forme `t + t·z·Q(z)` conserve la précision relative près de 0
17//! (jusqu'aux subnormaux).
18//!
19//! # Comportement
20//!
21//! | Entrée   | Sortie                       |
22//! |----------|------------------------------|
23//! | `±0.0`   | `±0.0` (signe conservé)      |
24//! | `±∞`     | `±π/2`                       |
25//! | `NaN`    | `NaN`                        |
26//!
27//! Résultat dans `[-π/2, π/2]`.
28
29use core::f32::consts::{FRAC_2_PI, FRAC_PI_2, FRAC_PI_4};
30
31const SIGN_BIT: u32 = 1 << 31;
32
33/// tan(3π/8) = 1 + √2
34const TAN_3PI_8: f32 = 2.414_213_6;
35/// tan(π/8) = √2 − 1
36const TAN_PI_8: f32 = 0.414_213_57;
37
38// Polynôme minimax : atan(t) ≈ t + t·z·(P0 + z·(P1 + z·(P2 + z·P3))).
39const P0: f32 = -0.333_329_5;
40const P1: f32 = 0.199_777_1;
41const P2: f32 = -0.138_776_86;
42const P3: f32 = 0.080_537_445;
43
44/// Arc tangente de `x`, en radians, dans `[-π/2, π/2]`.
45///
46/// Retourne `NaN` si `x` est `NaN`.
47pub fn atan(x: f32) -> f32 {
48    if x.is_nan() {
49        return x;
50    }
51
52    let bits = x.to_bits();
53    let a = f32::from_bits(bits & !SIGN_BIT);
54
55    let (base, t) = if a > TAN_3PI_8 {
56        (FRAC_PI_2, -1.0 / a)
57    } else if a > TAN_PI_8 {
58        (FRAC_PI_4, (a - 1.0) / (a + 1.0))
59    } else {
60        (0.0, a)
61    };
62
63    let z = t * t;
64    let p = (((P3 * z + P2) * z + P1) * z + P0) * z * t + t;
65    let r = base + p;
66
67    // Réapplique le signe (fonction impaire, conserve -0.0).
68    f32::from_bits(r.to_bits() | (bits & SIGN_BIT))
69}
70
71/// `atan(x)` normalisé dans `[-1, 1]` (c'est-à-dire `atan(x) · 2/π`).
72#[inline]
73pub fn atan_norm(x: f32) -> f32 {
74    atan(x) * FRAC_2_PI
75}
76
77#[cfg(test)]
78mod tests {
79    use super::*;
80    use core::f32::consts;
81
82    /// Erreur absolue tolérée (ulp de f32 près de π/2 : ~1,2·10⁻⁷).
83    const TOL: f32 = 5e-7;
84
85    fn ref_f64(x: f32) -> f64 {
86        (x as f64).atan()
87    }
88
89    #[test]
90    fn valeurs_remarquables() {
91        let s3 = 3.0f32.sqrt();
92        let vecteurs: &[(f32, f32)] = &[
93            (0.0, 0.0),
94            (s3 / 3.0, consts::FRAC_PI_6),
95            (1.0, consts::FRAC_PI_4),
96            (s3, consts::FRAC_PI_3),
97            (-s3 / 3.0, -consts::FRAC_PI_6),
98            (-1.0, -consts::FRAC_PI_4),
99            (-s3, -consts::FRAC_PI_3),
100        ];
101        for &(x, attendu) in vecteurs {
102            let r = atan(x);
103            assert!(
104                (r - attendu).abs() <= TOL,
105                "atan({x}) = {r}, attendu {attendu}"
106            );
107        }
108    }
109
110    #[test]
111    fn zeros_signes() {
112        assert_eq!(atan(0.0).to_bits(), 0.0f32.to_bits());
113        assert_eq!(atan(-0.0).to_bits(), (-0.0f32).to_bits());
114    }
115
116    #[test]
117    fn nan_reste_nan() {
118        assert!(atan(f32::NAN).is_nan());
119        assert!(atan(-f32::NAN).is_nan());
120        assert!(atan_norm(f32::NAN).is_nan());
121    }
122
123    #[test]
124    fn infinis() {
125        assert_eq!(atan(f32::INFINITY), FRAC_PI_2);
126        assert_eq!(atan(f32::NEG_INFINITY), -FRAC_PI_2);
127    }
128
129    #[test]
130    fn grandes_valeurs() {
131        for &x in &[1e3f32, 1e6, 1e12, 1e30, f32::MAX] {
132            for &s in &[1.0f32, -1.0] {
133                let x = s * x;
134                let err = (atan(x) as f64 - ref_f64(x)).abs();
135                assert!(err <= TOL as f64, "x = {x:e}, err = {err:e}");
136            }
137        }
138    }
139
140    #[test]
141    fn petites_valeurs_precision_relative() {
142        for &x in &[
143            1e-30f32,
144            -1e-30,
145            1e-10,
146            -1e-10,
147            1e-5,
148            f32::EPSILON,
149            f32::MIN_POSITIVE,
150            f32::from_bits(1),
151            f32::from_bits(SIGN_BIT | 1),
152        ] {
153            let got = atan(x) as f64;
154            let want = ref_f64(x);
155            assert!(((got - want) / want).abs() <= 1e-6, "x = {x:e}");
156        }
157    }
158
159    #[test]
160    fn symetrie_impaire_exacte() {
161        let mut x = 0.0f32;
162        while x <= 50.0 {
163            assert_eq!(atan(-x).to_bits(), (-atan(x)).to_bits(), "x = {x}");
164            x += 1.0 / 211.0;
165        }
166    }
167
168    #[test]
169    fn raccords_des_branches() {
170        // Balaie 128 flottants consécutifs autour de chaque seuil.
171        for &seuil in &[TAN_PI_8, TAN_3PI_8] {
172            let mut x = f32::from_bits(seuil.to_bits() - 64);
173            for _ in 0..128 {
174                let err = (atan(x) as f64 - ref_f64(x)).abs();
175                assert!(err <= TOL as f64, "x = {x}, err = {err:e}");
176                x = f32::from_bits(x.to_bits() + 1);
177            }
178        }
179    }
180
181    #[test]
182    fn identite_inverse() {
183        // atan(x) + atan(1/x) = π/2 pour x > 0
184        let mut x = 0.01f32;
185        while x < 100.0 {
186            let somme = atan(x) + atan(1.0 / x);
187            assert!(
188                (somme - FRAC_PI_2).abs() <= 2.0 * TOL,
189                "x = {x}, somme = {somme}"
190            );
191            x *= 1.013;
192        }
193    }
194
195    #[test]
196    fn dans_l_intervalle() {
197        for i in -50_000..=50_000 {
198            let x = (i as f32) / 100.0;
199            let r = atan(x);
200            assert!((-FRAC_PI_2..=FRAC_PI_2).contains(&r), "x = {x}, r = {r}");
201        }
202    }
203
204    #[test]
205    fn monotone_croissante() {
206        let mut prec = atan(-100.0);
207        for i in -99_999..=100_000 {
208            let x = (i as f32) / 1000.0;
209            let r = atan(x);
210            // Tolérance de bruit d'arrondi aux raccords.
211            assert!(r >= prec - 3e-7, "non monotone en x = {x}: {r} < {prec}");
212            prec = r;
213        }
214    }
215
216    #[test]
217    fn norm_dans_moins_un_un() {
218        assert!((atan_norm(1.0) - 0.5).abs() <= TOL);
219        assert!((atan_norm(-1.0) + 0.5).abs() <= TOL);
220        assert!((atan_norm(f32::INFINITY) - 1.0).abs() <= TOL);
221        assert!((atan_norm(f32::NEG_INFINITY) + 1.0).abs() <= TOL);
222    }
223
224    #[test]
225    fn balayage_vs_f64() {
226        let mut pire = 0.0f64;
227        // Échelle linéaire [-10, 10] puis logarithmique jusqu'à 1e30.
228        for i in -200_000..=200_000 {
229            let x = (i as f32) / 20_000.0;
230            let err = (atan(x) as f64 - ref_f64(x)).abs();
231            pire = pire.max(err);
232            assert!(err <= TOL as f64, "x = {x}, err = {err:e}");
233        }
234        let mut x = 10.0f32;
235        while x < 1e30 {
236            for &s in &[1.0f32, -1.0] {
237                let err = (atan(s * x) as f64 - ref_f64(s * x)).abs();
238                pire = pire.max(err);
239                assert!(err <= TOL as f64, "x = {}, err = {err:e}", s * x);
240            }
241            x *= 1.07;
242        }
243        std::println!("erreur max : {pire:e}");
244    }
245}