From a64cf66f4cc9bbfbb4a3252b2ba56f2f60de75b3 Mon Sep 17 00:00:00 2001 From: James Lucas Date: Sun, 18 Sep 2016 14:36:44 -0700 Subject: [PATCH 1/2] Implementing epsilon function to retrieve EPSILON constant --- traits/src/float.rs | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/traits/src/float.rs b/traits/src/float.rs index 66c174c..6b052c3 100644 --- a/traits/src/float.rs +++ b/traits/src/float.rs @@ -89,6 +89,18 @@ pub trait Float /// ``` fn min_positive_value() -> Self; + /// Returns epsilon, a small positive value. + /// + /// ``` + /// use num_traits::Float; + /// use std::f64; + /// + /// let x: f64 = Float::epsilon(); + /// + /// assert_eq!(x, f64::EPSILON); + /// ``` + fn epsilon() -> Self; + /// Returns the largest finite value that this type can represent. /// /// ``` @@ -936,6 +948,11 @@ macro_rules! float_impl { ::std::$T::MIN_POSITIVE } + #[inline] + fn epsilon() -> Self { + ::std::$T::EPSILON + } + #[inline] fn max_value() -> Self { ::std::$T::MAX From 381942eb4f023f11c1c2d92d54f03b92eb6312ea Mon Sep 17 00:00:00 2001 From: James Lucas Date: Thu, 22 Sep 2016 19:56:44 +0100 Subject: [PATCH 2/2] Adding default implementation --- traits/src/float.rs | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/traits/src/float.rs b/traits/src/float.rs index 6b052c3..757be87 100644 --- a/traits/src/float.rs +++ b/traits/src/float.rs @@ -2,6 +2,9 @@ use std::mem; use std::ops::Neg; use std::num::FpCategory; +// Used for default implementation of `epsilon` +use std::f32; + use {Num, NumCast}; // FIXME: these doctests aren't actually helpful, because they're using and @@ -99,7 +102,14 @@ pub trait Float /// /// assert_eq!(x, f64::EPSILON); /// ``` - fn epsilon() -> Self; + /// + /// # Panics + /// + /// The default implementation will panic if `f32::EPSILON` cannot + /// be cast to `Self`. + fn epsilon() -> Self { + Self::from(f32::EPSILON).expect("Unable to cast from f32::EPSILON") + } /// Returns the largest finite value that this type can represent. ///