jtempest / float_eq-rs

Compare IEEE floating point values for equality.
Other
39 stars 6 forks source link

Comparison of heterogeneous types #6

Closed jtempest closed 4 years ago

jtempest commented 4 years ago

Currently FloatEq is built with support for homogeneous types in mind, so for example:

assert_float_eq!([1., 2.], [1., 2.], ulps <= 4);
assert_float_eq!(
    MyType { a: 1., b: 2.},
    MyType { a: 1., b: 2. },
    rel <= 0.001
);

However, explicit support for heterogeneous epsilons might be useful, especially for tuple types. So, for example, you might be able to write comparisons along the lines of:

assert_float_eq!([1., 2.], [1., 2.], ulps <= [4, 8]);
assert_float_eq!((1_f32, 2_f64), (1., 2.), ulps <= (4, 8));
assert_float_eq!(
    MyType { a: 1., b: 2.},
    MyType { a: 1., b: 2. },
    rel <= MyType { a: 0.001, b: 0.005 }
);
jtempest commented 4 years ago

Implementing this via promoting the generic DiffEpsilon/UlpsDiffEpsilon associated types into generic params presents some issues:

Hence, I think we can go with a slightly clunkier but more straightforward design that allows for these comparisons by introducing three more *_all comparison types via a new trait (FloatEqAll?):

assert_float_eq!([1., 2.], [1., 2.], ulps <= [4, 8]);
assert_float_eq!((1_f32, 2_f64), (1., 2.), ulps <= (4, 8));
assert_float_eq!(
    MyType { a: 1., b: 2.},
    MyType { a: 1., b: 2. },
    rel <= MyType { a: 0.001, b: 0.005 }
);

assert_float_eq!([1., 2.], [1., 2.], ulps_all <= 4);
assert_float_eq!(
    MyType { a: 1., b: 2.},
    MyType { a: 1., b: 2. },
    rel_all <= 0.001
);

The default case is to destructure the comparison and specify it per field, since that's a more general case. This is a break from the currently implemented behaviour of FloatEq, but since the library is a month old and I suspect most users are using it for simple f32/f64 comparisons, I'm hoping the potential impact is low and can be mitigated by proper release documentation.

jtempest commented 4 years ago

This change landed in https://github.com/jtempest/float_eq-rs/commit/42ed9e14db2b2fe5b8a838ee21c5e202fb8ae100.