Browse Source

Merge remote-tracking branch 'origin/master' into fix/num-macros

Łukasz Jan Niemier 8 years ago
parent
commit
b038b79900
1 changed files with 27 additions and 0 deletions
  1. 27 0
      traits/src/float.rs

+ 27 - 0
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
@@ -89,6 +92,25 @@ 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);
+    /// ```
+    ///
+    /// # 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.
     ///
     /// ```
@@ -936,6 +958,11 @@ macro_rules! float_impl {
                 ::std::$T::MIN_POSITIVE
             }
 
+            #[inline]
+            fn epsilon() -> Self {
+                ::std::$T::EPSILON
+            }
+
             #[inline]
             fn max_value() -> Self {
                 ::std::$T::MAX