Assert_eq!() giving weird results with f32!

⚓ Rust    📅 2026-01-06    👤 surdeus    👁️ 4      

surdeus

So, I have a test case that uses an array of f32 values. It creates a clone of that array, "randomizes" the order of the values, and then brings them back into the "correct" order (by swapping the elements as needed). Finally, I will compare the "test" array (clone) to the original one, element by element, to verify that each element indeed ended up at the initial position.

Code looks like this:

fn assert_arrays_equal_f32(array_a: &[f32], array_b: &[f32]) {
    assert_eq!(array_a.len(), array_b.len());
    for (a, b) in array_a.iter().copied().zip(array_b.iter().copied()) {
        assert_eq!(a, b);
    }
}

Now, the weird thing is that this test works perfectly fine on Linux and on Windows, but fails on MacOS only! I understand that assert_eq!(a, b) can be "problematic" if floating point values are "very close" but not exactly the same. But this can not be the problem here, as I just move around the values, not do any FP math with them. They should match exactly!


I have added some extra debug outputs:

fn assert_arrays_equal_f32(array_a: &[f32], array_b: &[f32]) {
    assert_eq!(array_a.len(), array_b.len());
    for (a, b) in array_a.iter().copied().zip(array_b.iter().copied()) {
        if !(a == b) {
            println!("{:.16} != {:.16}", a, b);
            println!("{:08X} != {:08X}", a.to_bits(), b.to_bits());
            panic!("Did *not* match!");
        }
        assert_eq!(a, b);
    }
}

Output on MacOS, where the test fails:

-1.0000000000000000 != -1.0000000000000000
BF800000 != BF800000

thread 'test_float_3a' (11369) panicked at tests/float_test.rs:18:13:
Did *not* match!

How the heck is this possible? :exploding_head:

Clearly, the floating point numbers are exactly the same. Their bit-representation is the same!

Still, they compare not equal ???

And why does this only happen on the MacOS runner, not on Linux or Windows? :face_with_raised_eyebrow:

This is with Rust 1.92.0, byte the way.

Any ideas ???

Thank you and best regards.

15 posts - 8 participants

Read full topic

🏷️ Rust_feed