// Copyright 2014-2018 Optimal Computing (NZ) Ltd. // Licensed under the MIT license. See LICENSE for details.
use std::cmp::PartialOrd; use std::ops::{Sub,Div,Neg}; use num_traits::Zero;
/// ApproxEqRatio is a trait for approximate equality comparisons bounding the ratio /// of the difference to the larger. pubtrait ApproxEqRatio : Div<Output = Self> + Sub<Output = Self> + Neg<Output = Self>
+ PartialOrd + Zero + Sized + Copy
{ /// This method tests if `self` and `other` are nearly equal by bounding the /// difference between them to some number much less than the larger of the two. /// This bound is set as the ratio of the difference to the larger. fn approx_eq_ratio(&self, other: &Self, ratio: Self) -> bool {
// Not equal if signs are not equal if *self < Self::zero() && *other > Self::zero() { returnfalse; } if *self > Self::zero() && *other < Self::zero() { returnfalse; }
// Handle all zero cases match (*self == Self::zero(), *other == Self::zero()) {
(true,true) => returntrue,
(true,false) => returnfalse,
(false,true) => returnfalse,
_ => { }
}
// abs let (s,o) = if *self < Self::zero() {
(-*self, -*other)
} else {
(*self, *other)
};
let (smaller,larger) = if s < o {
(s,o)
} else {
(o,s)
}; let difference: Self = larger.sub(smaller); let actual_ratio: Self = difference.div(larger);
actual_ratio < ratio
}
/// This method tests if `self` and `other` are not nearly equal by bounding the /// difference between them to some number much less than the larger of the two. /// This bound is set as the ratio of the difference to the larger. #[inline] fn approx_ne_ratio(&self, other: &Self, ratio: Self) -> bool {
!self.approx_eq_ratio(other, ratio)
}
}
#[test] fn f32_approx_eq_ratio_test_negative_numbers() { let x: f32 = -3.0_f32; let y: f32 = -4.0_f32; // -3 and -4 should not be equal at a ratio of 0.1
assert!(x.approx_eq_ratio(&y,0.1) == false);
}
#[test] fn f64_approx_eq_ratio_test_negative_numbers() { let x: f64 = -3.0_f64; let y: f64 = -4.0_f64; // -3 and -4 should not be equal at a ratio of 0.1
assert!(x.approx_eq_ratio(&y,0.1) == false);
}
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.10 Sekunden
(vorverarbeitet am 2026-06-18)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.