Comparing floats (revisited)

That seems to work:

use anyhow::Error;

fn main() {
    let a: f64 = 0.000002;
    let b: f64 = 0.000001;
    assert!(a > b);

    let it = testomato(a, b).expect("nope");
    println!("{:?}", it);
}

fn testomato(a: f64, b: f64) -> Result<(f64, f64), Error> {
    anyhow::ensure!(a > b);
    Ok((a, b))
}

And this is not an illusion[1], or a mistake in my thinking?


  1. Since I've read a lot of comments on this subject, none of which really got to the point. ↩︎

Any float type with at least 2 bits* of mantissa and sufficient exponent bits can order those particular values the way you'd expect. Especially since no NaNs are involved.

(*) Maybe 3 or 4. I'd have to pull up some analysis tools to be sure.

1 Like

I'm not really sure what the question is, but if you want to see all the digits without with less rounding you can look at this code snippet:

fn main() {
    let a: f64 = 0.000002;
    let b: f64 = 0.000001;
    assert!(a > b);
    println!("a: {a:.75}, b: {b:.75}");
}
1 Like

Keep in mind that println and such display rounded values, because exact values may not be possible to print in decimal form (in the same way 1/3 isn't possible to print exactly in decimal).

https://0.30000000000000004.com

2 Likes

Compare https://float.exposed/0x3ec0c6f7a0b5ed8d & https://float.exposed/0x3eb0c6f7a0b5ed8d.

1 Like

Thanks.

Thanks