Search code examples
rustfloating-point

How to handle overflows in operations for floating numbers such as f64 in Rust


I want to do something like this so I can handle cases where my expressions overflow

fn add(a : f64, b: f64) -> Result<f64, OverflowError>{
  a.checked_add(b)?
}

But I could not find any way to do it.


Solution

  • Floating point operations do not overflow. Instead, they saturate to something, such as positive infinity, negative infinity, or NaN (for e.g. division by zero or operations on infinities of different signs).

    You can use is_finite to see if a floating point value is neither infinity nor NaN. Typically, you would do all of the floating point arithmetic you need and then perform one final check at the end instead of testing each intermediate value.

    You can combine is_finite with then_some if you want to produce an Option where it's only Some if it's finite. For example:

    fn add(a: f64, b: f64) -> Option<f64> {
        let r = a + b;
    
        r.is_finite().then_some(r)
    }