#float #f64 #f32 #nextafter #increment

float_next_after

A trait for native rust f64/f32 nextafter

6 releases

0.1.5 Apr 13, 2020
0.1.4 Apr 13, 2020

#158 in Math

Download history 2234/week @ 2021-08-12 3412/week @ 2021-08-19 3263/week @ 2021-08-26 2599/week @ 2021-09-02 3030/week @ 2021-09-09 4410/week @ 2021-09-16 3378/week @ 2021-09-23 3674/week @ 2021-09-30 2913/week @ 2021-10-07 4426/week @ 2021-10-14 5408/week @ 2021-10-21 5591/week @ 2021-10-28 3336/week @ 2021-11-04 3263/week @ 2021-11-11 2739/week @ 2021-11-18 2297/week @ 2021-11-25

12,071 downloads per month
Used in 60 crates (5 directly)

MIT license

20KB
376 lines

float-next-after

A native Rust next after float function, which is provided as a trait for f32 and f64 types. It steps to the next representable floating point, even if it is subnormal. If a subnormal is undesired, users should handle that eventuality themselves.

In specific edge cases the following decisions have been made:

  • self == y -> return y
  • self >= positive infinity -> return positive infinity
  • self <= negative infinity -> return negative infinity
  • self or y == NaN -> return NaN
  • self = -0.0 and y = 0.0 -> return positive 0.0
  • self == -0.0 and y == positive infinity -> 5e-324

Please see the unit tests for the actual behavior in various other exceptional cases.

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

PR's and other helpful input are welcome.

Usage

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);

Dependencies

~140KB