Skip to content

Commit

Permalink
Auto merge of #231 - AtheMathmo:generic-epsilon, r=hauleth
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
homu committed Sep 22, 2016
2 parents a11be64 + 381942e commit 338e479
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions traits/src/float.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
///
/// ```
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 338e479

Please sign in to comment.