diff --git a/base/src/approx_f64.rs b/base/src/approx_f64.rs index 4a7a826e7..4a58a0897 100644 --- a/base/src/approx_f64.rs +++ b/base/src/approx_f64.rs @@ -1,3 +1,4 @@ +use std::cmp::Ordering; use std::fmt::{Display, Formatter}; /// An approximate floating-point type that uses the same epsilon for comparison as the == operator in @@ -9,7 +10,7 @@ pub type AudioF64 = ApproxF64<100000>; /// /// The const type parameter `E` ("epsilon") defines how tolerant floating-point comparison is. Two values are considered /// equal if the difference is less than 1/E. -#[derive(Copy, Clone, PartialOrd, Debug, Default)] +#[derive(Copy, Clone, Debug, Default)] pub struct ApproxF64(pub f64); impl ApproxF64 { @@ -18,11 +19,24 @@ impl ApproxF64 { pub fn new(raw: f64) -> Self { Self(raw) } + + fn difference_is_neglectable(&self, other: &Self) -> bool { + (self.0 - other.0).abs() < Self::EPSILON + } +} + +impl PartialOrd for ApproxF64 { + fn partial_cmp(&self, other: &Self) -> Option { + if self.difference_is_neglectable(other) { + return Some(Ordering::Equal); + } + self.0.partial_cmp(&other.0) + } } impl PartialEq for ApproxF64 { fn eq(&self, other: &Self) -> bool { - (self.0 - other.0).abs() < Self::EPSILON + self.difference_is_neglectable(other) } }