| 1 | # float-cmp |
| 2 | |
| 3 | [](https://travis-ci.org/mikedilger/float-cmp) |
| 4 | [](./LICENSE) |
| 5 | |
| 6 | Documentation is available at https://docs.rs/float-cmp |
| 7 | |
| 8 | float-cmp defines and implements traits for approximate comparison of floating point types |
| 9 | which have fallen away from exact equality due to the limited precision available within |
| 10 | floating point representations. Implementations of these traits are provided for `f32` |
| 11 | and `f64` types. |
| 12 | |
| 13 | When I was a kid in the '80s, the programming rule was "Never compare floating point |
| 14 | numbers". If you can follow that rule and still get the outcome you desire, then more |
| 15 | power to you. However, if you really do need to compare them, this crate provides a |
| 16 | reasonable way to do so. |
| 17 | |
| 18 | Another crate `efloat` offers another solution by providing a floating point type that |
| 19 | tracks its error bounds as operations are performed on it, and thus can implement the |
| 20 | `ApproxEq` trait in this crate more accurately, without specifying a `Margin`. |
| 21 | |
| 22 | The recommended go-to solution (although it may not be appropriate in all cases) is the |
| 23 | `approx_eq()` function in the `ApproxEq` trait (or better yet, the macros). For `f32` |
| 24 | and `f64`, the `F32Margin` and `F64Margin` types are provided for specifying margins as |
| 25 | both an epsilon value and an ULPs value, and defaults are provided via `Default` |
| 26 | (although there is no perfect default value that is always appropriate, so beware). |
| 27 | |
| 28 | Several other traits are provided including `Ulps`, `ApproxEqUlps`, `ApproxOrdUlps`, and |
| 29 | `ApproxEqRatio`. |
| 30 | |
| 31 | ## The problem |
| 32 | |
| 33 | Floating point operations must round answers to the nearest representable number. Multiple |
| 34 | operations may result in an answer different from what you expect. In the following example, |
| 35 | the assert will fail, even though the printed output says "0.45 == 0.45": |
| 36 | |
| 37 | ```rust |
| 38 | let a: f32 = 0.15 + 0.15 + 0.15; |
| 39 | let b: f32 = 0.1 + 0.1 + 0.25; |
| 40 | println!("{} == {}", a, b); |
| 41 | assert!(a==b) // Fails, because they are not exactly equal |
| 42 | ``` |
| 43 | |
| 44 | This fails because the correct answer to most operations isn't exactly representable, and so |
| 45 | your computer's processor chooses to represent the answer with the closest value it has |
| 46 | available. This introduces error, and this error can accumulate as multiple operations are |
| 47 | performed. |
| 48 | |
| 49 | ## The solution |
| 50 | |
| 51 | With `ApproxEq`, we can get the answer we intend: |
| 52 | ```rust |
| 53 | let a: f32 = 0.15 + 0.15 + 0.15; |
| 54 | let b: f32 = 0.1 + 0.1 + 0.25; |
| 55 | println!("{} == {}", a, b); |
| 56 | assert!( approx_eq!(f32, a, b, ulps = 2) ); |
| 57 | ``` |
| 58 | |
| 59 | ## Some explanation |
| 60 | |
| 61 | We use the term ULP (units of least precision, or units in the last place) to mean the |
| 62 | difference between two adjacent floating point representations (adjacent meaning that there is |
| 63 | no floating point number between them). This term is borrowed from prior work (personally I |
| 64 | would have chosen "quanta"). The size of an ULP (measured as a float) varies |
| 65 | depending on the exponents of the floating point numbers in question. That is a good thing, |
| 66 | because as numbers fall away from equality due to the imprecise nature of their representation, |
| 67 | they fall away in ULPs terms, not in absolute terms. Pure epsilon-based comparisons are |
| 68 | absolute and thus don't map well to the nature of the additive error issue. They work fine |
| 69 | for many ranges of numbers, but not for others (consider comparing -0.0000000028 |
| 70 | to +0.00000097). |
| 71 | |
| 72 | ## Using this crate |
| 73 | |
| 74 | By default this crate enables the `ratio` module providing the `ApproxEqRatio` trait. This |
| 75 | feature pulls in `num-traits`. If you disable this feature, you'll need to either enable |
| 76 | `num-traits` directly or else enable the `std` feature; otherwise it won't compile. This crate |
| 77 | is `#![no_std]` unless you enable the `std` feature. |
| 78 | |
| 79 | You can use the `ApproxEq` trait directly like so: |
| 80 | |
| 81 | ```rust |
| 82 | assert!( a.approx_eq(b, F32Margin { ulps: 2, epsilon: 0.0 }) ); |
| 83 | ``` |
| 84 | |
| 85 | We have implemented `From<(f32,i32)>` for `F32Margin` (and similarly for `F64Margin`) |
| 86 | so you can use this shorthand: |
| 87 | |
| 88 | ```rust |
| 89 | assert!( a.approx_eq(b, (0.0, 2)) ); |
| 90 | ``` |
| 91 | |
| 92 | With macros, it is easier to be explicit about which type of margin you wish to set, |
| 93 | without mentioning the other one (the other one will be zero). But the downside is |
| 94 | that you have to specify the type you are dealing with: |
| 95 | |
| 96 | ```rust |
| 97 | assert!( approx_eq!(f32, a, b, ulps = 2) ); |
| 98 | assert!( approx_eq!(f32, a, b, epsilon = 0.00000003) ); |
| 99 | assert!( approx_eq!(f32, a, b, epsilon = 0.00000003, ulps = 2) ); |
| 100 | assert!( approx_eq!(f32, a, b, (0.0, 2)) ); |
| 101 | assert!( approx_eq!(f32, a, b, F32Margin { epsilon: 0.0, ulps: 2 }) ); |
| 102 | assert!( approx_eq!(f32, a, b, F32Margin::default()) ); |
| 103 | assert!( approx_eq!(f32, a, b) ); // uses the default |
| 104 | ``` |
| 105 | |
| 106 | For most cases, I recommend you use a smallish integer for the `ulps` parameter (1 to 5 |
| 107 | or so), and a similar small multiple of the floating point's EPSILON constant (1.0 to 5.0 |
| 108 | or so), but there are *plenty* of cases where this is insufficient. |
| 109 | |
| 110 | ## Implementing these traits |
| 111 | |
| 112 | You can implement `ApproxEq` for your own complex types like shown below. |
| 113 | The floating point type `F` must be `Copy`, but for large types you can implement |
| 114 | it for references to your type as shown. |
| 115 | |
| 116 | ```rust |
| 117 | use float_cmp::ApproxEq; |
| 118 | |
| 119 | pub struct Vec2<F> { |
| 120 | pub x: F, |
| 121 | pub y: F, |
| 122 | } |
| 123 | |
| 124 | impl<'a, M: Copy, F: Copy + ApproxEq<Margin=M>> ApproxEq for &'a Vec2<F> { |
| 125 | type Margin = M; |
| 126 | |
| 127 | fn approx_eq<T: Into<Self::Margin>>(self, other: Self, margin: T) -> bool { |
| 128 | let margin = margin.into(); |
| 129 | self.x.approx_eq(other.x, margin) |
| 130 | && self.y.approx_eq(other.y, margin) |
| 131 | } |
| 132 | } |
| 133 | ``` |
| 134 | |
| 135 | ## Non floating-point types |
| 136 | |
| 137 | `ApproxEq` can be implemented for non floating-point types as well, since `Margin` is |
| 138 | an associated type. |
| 139 | |
| 140 | The `efloat` crate implements (or soon will implement) `ApproxEq` for a compound type |
| 141 | that tracks floating point error bounds by checking if the error bounds overlap. |
| 142 | In that case `type Margin = ()`. |
| 143 | |
| 144 | ## Inspiration |
| 145 | |
| 146 | This crate was inspired by this Random ASCII blog post: |
| 147 | |
| 148 | [https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/](https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/) |