Skip to content

Commit 338e479

Browse files
committed
Auto merge of #231 - AtheMathmo:generic-epsilon, r=hauleth
Implementing epsilon function to retrieve EPSILON constant Hey! This PR exposes a new `epsilon` function in the `Float` trait so that users can access the `EPSILON` constant on the float types. I figured as this was such a minimal change it was easier to get a PR in offering the change then write up an issue. For me this is a valuable addition. When writing linear algebra or other optimization routines with generic floats we often want to check if some stopping criteria is reached, often something like: `(a - b).abs() < eps`. Having access to a standard _small value_ would make this a little easier.
2 parents a11be64 + 381942e commit 338e479

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

traits/src/float.rs

+27
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,9 @@ use std::mem;
22
use std::ops::Neg;
33
use std::num::FpCategory;
44

5+
// Used for default implementation of `epsilon`
6+
use std::f32;
7+
58
use {Num, NumCast};
69

710
// FIXME: these doctests aren't actually helpful, because they're using and
@@ -89,6 +92,25 @@ pub trait Float
8992
/// ```
9093
fn min_positive_value() -> Self;
9194

95+
/// Returns epsilon, a small positive value.
96+
///
97+
/// ```
98+
/// use num_traits::Float;
99+
/// use std::f64;
100+
///
101+
/// let x: f64 = Float::epsilon();
102+
///
103+
/// assert_eq!(x, f64::EPSILON);
104+
/// ```
105+
///
106+
/// # Panics
107+
///
108+
/// The default implementation will panic if `f32::EPSILON` cannot
109+
/// be cast to `Self`.
110+
fn epsilon() -> Self {
111+
Self::from(f32::EPSILON).expect("Unable to cast from f32::EPSILON")
112+
}
113+
92114
/// Returns the largest finite value that this type can represent.
93115
///
94116
/// ```
@@ -936,6 +958,11 @@ macro_rules! float_impl {
936958
::std::$T::MIN_POSITIVE
937959
}
938960

961+
#[inline]
962+
fn epsilon() -> Self {
963+
::std::$T::EPSILON
964+
}
965+
939966
#[inline]
940967
fn max_value() -> Self {
941968
::std::$T::MAX

0 commit comments

Comments
 (0)