# Crate float_cmp [−] [src]

Defines traits `ApproxEqUlps`, `ApproxOrdUlps`, and `Ulps`, for approximate comparison of floating point types which have fallen away from equality due to rounding and inaccuracies within the floating point system. Defines implementations for `f32` and `f64`.

Also defines `ApproxEqRatio` and `ApproxOrdRatio` to define a notion of "close enough" based on the ratio of the difference to the larger.

Floating point operations must round answers to the nearest representable number. Multiple operations may result in an answer different from what you expect. In the following example the assert will fail, even though the printed output says "0.45 == 0.45":

``````  let a = 0.15_f32 + 0.15_f32 + 0.15_f32;
let b = 0.1_f32 + 0.1_f32 + 0.25_f32;
println!("{} == {}", a, b);
assert!(a==b)  // Fails, because they are not exactly equal
``````

This fails due to rounding and inaccuracies within the floating point system. With `ApproxEqUlps`, we can get the answer we intend:

```  let a = 0.15_f32 + 0.15_f32 + 0.15_f32;
let b = 0.1_f32 + 0.1_f32 + 0.25_f32;
println!("{} == {}", a, b);
assert!(a.approx_eq_ulps(&b,2)) // They are equal, within 2 ulps```

We use the term ULP (units of least precision, or units in the last place) to mean the difference between two adjacent floating point representations (adjacent meaning that there is no floating point number between them). The size of an ulp (measured as a float) varies depending on the exponents of the floating point numbers in question, but this is quite useful, for it is the non-variation of a fixed epsilon (e.g. 0.0000001) which causes epsilon-based comparisons to so often fail with more extreme floating point values.

What we do is define approximate comparison by specifying the maximum number of ULPs that the comparands are allowed to differ by.

## Traits

 ApproxEqRatio ApproxEqRatio is a trait for approximate equality comparisons bounding the ratio of the difference to the larger. ApproxEqUlps ApproxEqUlps is a trait for approximate equality comparisons, and is defined only for floating point types. ApproxOrdUlps ApproxOrdUlps is for sorting floating point values where approximate equality is considered equal. Ulps A trait for floating point numbers which computes the number of representable values or ULPs (Units of Least Precision) that separate the two given values.