Skip to main content

spatialrust_math/
tolerance.rs

1/// Default tolerance for `f32` comparisons.
2#[must_use]
3pub const fn f32_eps() -> f32 {
4    1e-6
5}
6
7/// Default tolerance for `f64` comparisons.
8#[must_use]
9pub const fn f64_eps() -> f64 {
10    1e-12
11}
12
13/// Returns whether two values are approximately equal.
14#[must_use]
15pub fn approx_eq(a: f32, b: f32, epsilon: f32) -> bool {
16    (a - b).abs() <= epsilon
17}
18
19/// Returns whether two values are approximately equal.
20#[must_use]
21pub fn approx_eq_f64(a: f64, b: f64, epsilon: f64) -> bool {
22    (a - b).abs() <= epsilon
23}
24
25/// Returns whether a value is near zero.
26#[must_use]
27pub fn near_zero(value: f32, epsilon: f32) -> bool {
28    value.abs() <= epsilon
29}
30
31/// Returns whether a value is near zero.
32#[must_use]
33pub fn near_zero_f64(value: f64, epsilon: f64) -> bool {
34    value.abs() <= epsilon
35}
36
37#[cfg(test)]
38mod tests {
39    use super::{approx_eq, f32_eps, near_zero};
40
41    #[test]
42    fn approx_eq_works() {
43        assert!(approx_eq(1.0, 1.0 + 1e-7, f32_eps()));
44        assert!(!approx_eq(1.0, 1.1, f32_eps()));
45        assert!(near_zero(1e-7, f32_eps()));
46    }
47}