Skip to content

Commit

Permalink
#1164 Make ApproxF64 also have approximate ordering
Browse files Browse the repository at this point in the history
  • Loading branch information
helgoboss committed Sep 8, 2024
1 parent 7bfca47 commit a7b88de
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions base/src/approx_f64.rs
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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<const E: u32>(pub f64);

impl<const E: u32> ApproxF64<E> {
Expand All @@ -18,11 +19,24 @@ impl<const E: u32> ApproxF64<E> {
pub fn new(raw: f64) -> Self {
Self(raw)
}

fn difference_is_neglectable(&self, other: &Self) -> bool {
(self.0 - other.0).abs() < Self::EPSILON
}
}

impl<const E: u32> PartialOrd for ApproxF64<E> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
if self.difference_is_neglectable(other) {
return Some(Ordering::Equal);
}
self.0.partial_cmp(&other.0)
}
}

impl<const E: u32> PartialEq for ApproxF64<E> {
fn eq(&self, other: &Self) -> bool {
(self.0 - other.0).abs() < Self::EPSILON
self.difference_is_neglectable(other)
}
}

Expand Down

0 comments on commit a7b88de

Please sign in to comment.