A question about NaN

When I use floating point, oftentimes a NaN cropping up signals a bug in my program. That is, I maintain an implied invariant that all numbers are not NaNs, ha-ha.

I think this is a most common use case for floats, and it makes me wonder, why there is no a widely used floating type in Rust, which does not allow NaNs (in debug)? Something like

struct Real(f64);

impl From<f64> for Real {
  fn from(value: f64) -> Real {
    debug_assert!(!value.is_nan());
    Real(value)
  }
}

impl Ord for Real { .. }

NotNaN from ordered-float is close, but it includes checks even in release (which I assume affects performance) and it is not really widely used.

2 Likes

In both C++11 and D language there are standard ways to turn on signaling NaNs, that raise exceptions. Perhaps there's a similar way to activate NaNs that panic in Rust.

There's numeric-float, which may or may not be what you want.

1 Like