ferravex_math/
deterministic.rs

1//! Explicit arithmetic for simulation that must avoid platform libm variation.
2//! These helpers do not make an entire game deterministic by themselves.
3/// Sine/cosine with fixed f64 range reduction and polynomial evaluation, then
4/// one f32 rounding. No platform trig calls or fused multiply-add operations.
5/// Nonfinite input returns NaNs. Intended for bounded game input angles; huge
6/// angles lose reduction accuracy. Absolute error is below 2e-7 for [-2π,2π].
7pub fn sin_cos(angle: f32) -> (f32, f32) {
8    if !angle.is_finite() {
9        return (f32::NAN, f32::NAN);
10    }
11    let mut x = f64::from(angle) % std::f64::consts::TAU;
12    if x > std::f64::consts::PI {
13        x -= std::f64::consts::TAU;
14    }
15    if x < -std::f64::consts::PI {
16        x += std::f64::consts::TAU;
17    }
18    let mut sign = 1.;
19    if x > std::f64::consts::FRAC_PI_2 {
20        x = std::f64::consts::PI - x;
21        sign = -1.;
22    } else if x < -std::f64::consts::FRAC_PI_2 {
23        x = -std::f64::consts::PI - x;
24        sign = -1.;
25    }
26    let z = x * x;
27    // Horner evaluation, highest coefficient first (through x^21 / x^20).
28    let s = 1. / 51090942171709440000.;
29    let s = -1. / 121645100408832000. + z * s;
30    let s = 1. / 355687428096000. + z * s;
31    let s = -1. / 1307674368000. + z * s;
32    let s = 1. / 6227020800. + z * s;
33    let s = -1. / 39916800. + z * s;
34    let s = 1. / 362880. + z * s;
35    let s = -1. / 5040. + z * s;
36    let s = 1. / 120. + z * s;
37    let s = -1. / 6. + z * s;
38    let s = x * (1. + z * s);
39    let c = 1. / 2432902008176640000.;
40    let c = -1. / 6402373705728000. + z * c;
41    let c = 1. / 20922789888000. + z * c;
42    let c = -1. / 87178291200. + z * c;
43    let c = 1. / 479001600. + z * c;
44    let c = -1. / 3628800. + z * c;
45    let c = 1. / 40320. + z * c;
46    let c = -1. / 720. + z * c;
47    let c = 1. / 24. + z * c;
48    let c = -1. / 2. + z * c;
49    let c = sign * (1. + z * c);
50    (s as f32, c as f32)
51}
52#[cfg(test)]
53mod tests {
54    use super::*;
55    #[test]
56    fn input_angle_accuracy_symmetry_and_unit_length() {
57        for i in -20000..=20000 {
58            let angle = i as f32 * std::f32::consts::TAU / 20000.;
59            let (s, c) = sin_cos(angle);
60            assert!((s - angle.sin()).abs() < 2e-7, "sin {angle}");
61            assert!((c - angle.cos()).abs() < 2e-7, "cos {angle}");
62            assert!((s * s + c * c - 1.).abs() < 2e-7);
63            let (ns, nc) = sin_cos(-angle);
64            assert_eq!(s.to_bits() ^ 0x80000000, ns.to_bits());
65            assert_eq!(c.to_bits(), nc.to_bits());
66        }
67        assert!(sin_cos(f32::INFINITY).0.is_nan());
68    }
69}