Skip to content

Commit

Permalink
Fix acos() behavior for zero/negative, and add tests (#79)
Browse files Browse the repository at this point in the history
Co-authored-by: Tim Boldt <tim.boldt@gmail.com>
Co-authored-by: Tony Arcieri <bascule@gmail.com>
  • Loading branch information
3 people committed Apr 24, 2021
1 parent ed99288 commit b7f6919
Showing 1 changed file with 47 additions and 4 deletions.
51 changes: 47 additions & 4 deletions src/float/acos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,67 @@
//! <https://math.stackexchange.com/questions/2908908/express-arccos-in-terms-of-arctan>

use super::F32;
use core::f32::consts::PI;

impl F32 {
/// Computes `acos(x)` approximation in radians in the range `[0, pi]`.
pub(crate) fn acos(self) -> Self {
((Self::ONE - self * self).sqrt() / self).atan()
if self > 0.0 {
((Self::ONE - self * self).sqrt() / self).atan()
} else if self == 0.0 {
Self(PI / 2.0)
} else {
((Self::ONE - self * self).sqrt() / self).atan() + PI
}
}
}

#[cfg(test)]
mod tests {
use super::F32;
use core::f32::consts::FRAC_PI_4;
use core::f32::consts;

const MAX_ERROR: f32 = 0.03;

#[test]
fn sanity_check() {
let difference = F32(FRAC_PI_4).cos().acos() - FRAC_PI_4;
assert!(difference.abs() <= MAX_ERROR);
// Arccosine test vectors - `(input, output)`
let test_vectors: &[(f32, f32)] = &[
(2.000, f32::NAN),
(1.000, 0.0),
(0.866, consts::FRAC_PI_6),
(0.707, consts::FRAC_PI_4),
(0.500, consts::FRAC_PI_3),
(f32::EPSILON, consts::FRAC_PI_2),
(0.000, consts::FRAC_PI_2),
(-f32::EPSILON, consts::FRAC_PI_2),
(-0.500, 2.0 * consts::FRAC_PI_3),
(-0.707, 3.0 * consts::FRAC_PI_4),
(-0.866, 5.0 * consts::FRAC_PI_6),
(-1.000, consts::PI),
(-2.000, f32::NAN),
];

for &(x, expected) in test_vectors {
let actual = F32(x).acos();
if expected.is_nan() {
assert!(
actual.is_nan(),
"acos({}) returned {}, should be NAN",
x,
actual
);
} else {
let delta = (actual - expected).abs();

assert!(
delta <= MAX_ERROR,
"delta {} too large: {} vs {}",
delta,
actual,
expected
);
}
}
}
}

0 comments on commit b7f6919

Please sign in to comment.