How to compare floating point numbers
-
Determine which comparison algorithm best suits your purposes.
-
Determine the tolerance required based on the sources of the error in how the numbers were entered/calculated.
-
If you need a boolean result, then use
float_eq!
orfloat_ne!
. The two numbers should be the first and second operands, and then the tolerance is the value after the<=
. For example, to compare twof32
numbers stored ina
andb
using a relative tolerance oftol
scaled to the magnitude of the second operand:
#![allow(unused)] fn main() { float_eq!(a, b, r2nd <= tol) }
- If instead you wish to assert that the two numbers are equal and panic if
they are not, you can use
assert_float_eq!
orassert_float_ne!
. The syntax is the same, and may optionally include formatted text after the comparisons as with standard Rust asserts:
#![allow(unused)] fn main() { assert_float_eq!(a, b, r2nd <= tol); assert_float_eq!(a, b, r2nd <= tol, "Example context: {}", context); }