Skip to main content

NextAfter

Trait NextAfter 

Source
pub trait NextAfter {
    // Required method
    fn next_after(self, y: Self) -> Self;
}
Expand description

Returns the next representable float value in the direction of y

This function is compatible with the C standard library’s nextafter function and follows IEEE 754 floating-point semantics. It will step to the very next representable floating point, even if that value is subnormal.

§Behavior

  • self == y → returns y
  • self is NaN or y is NaN → returns NaN
  • self == +infinity and y < self → returns MAX (largest finite f64/f32)
  • self == -infinity and y > self → returns MIN (smallest finite f64/f32)
  • self == +infinity and y == +infinity → returns +infinity
  • self == -infinity and y == -infinity → returns -infinity
  • self == ±0.0 and y > 0 → returns smallest positive subnormal
  • self == ±0.0 and y < 0 → returns smallest negative subnormal
  • self == -0.0 and y == +0.0 → returns +0.0
  • self == +0.0 and y == -0.0 → returns -0.0

§Examples

use float_next_after::NextAfter;

// Large numbers
let big_num = 16237485966.00000437586943_f64;
let next = big_num.next_after(std::f64::INFINITY);
assert_eq!(next, 16237485966.000006_f64);

// Expected handling of 1.0
let one = 1_f64;
let next = one.next_after(std::f64::INFINITY);
assert_eq!(next, 1_f64 + std::f64::EPSILON);

// Tiny (negative) numbers
let zero = 0_f32;
let next = zero.next_after(std::f32::NEG_INFINITY);
assert_eq!(next, -0.000000000000000000000000000000000000000000001_f32);

// Equal source/dest (even -0 == 0)
let zero = 0_f64;
let next = zero.next_after(-0_f64);
assert_eq!(next, -0_f64);

§Safety

This trait uses the ToBits and FromBits functions from f32 and f64. Those both use unsafe { mem::transmute(self) } / unsafe { mem::transmute(v) } to convert a f32/f64 to u32/u64. The docs for those functions claim they are safe and that “the safety issues with sNaN were overblown!”

Required Methods§

Source

fn next_after(self, y: Self) -> Self

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementations on Foreign Types§

Source§

impl NextAfter for f32

Source§

fn next_after(self, y: Self) -> Self

Source§

impl NextAfter for f64

Source§

fn next_after(self, y: Self) -> Self

Implementors§