ballpark 1.0.1

Approximate comparisons for floating-point numbers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
//! Implementations for `libcore` types and builtin types.

use core::cell::{Cell, OnceCell, RefCell};

use super::ApproxEq;

macro_rules! base_impls {
    ($($float:ty),+) => { $(
        impl ApproxEq for $float {
            type Tolerance = Self;

            fn abs_eq(&self, other: &Self, abs_tolerance: Self::Tolerance) -> bool {
                assert!(abs_tolerance >= 0.0, "comparison tolerance must be non-negative and not NaN");

                if self.is_nan() || other.is_nan() {
                    // Ensure that `nan != X` and `X != nan`.
                    return false;
                }
                if !self.is_finite() && !other.is_finite() && self == other {
                    // Ensure that `inf == inf` and `-inf == -inf`.
                    return true;
                }

                let diff = (self - other).abs();
                diff <= abs_tolerance
            }

            fn rel_eq(&self, other: &Self, rel_tolerance: Self::Tolerance) -> bool {
                assert!(rel_tolerance >= 0.0, "comparison tolerance must be non-negative and not NaN");

                if self.is_nan() || other.is_nan() {
                    // Ensure that `nan != X` and `X != nan`.
                    return false;
                }
                if !self.is_finite() && !other.is_finite() && self == other {
                    // Ensure that `inf == inf` and `-inf == -inf`.
                    return true;
                }

                let abs_diff = (self - other).abs();
                let abs_self = self.abs();
                let abs_other = other.abs();
                let largest = Self::max(abs_self, abs_other);

                abs_diff <= largest * rel_tolerance
            }

            #[allow(irrefutable_let_patterns)]
            fn ulps_eq(&self, other: &Self, ulps_tolerance: u32) -> bool {
                if self.is_nan() || other.is_nan() {
                    // Ensure that `nan != X` and `X != nan`.
                    return false;
                }

                // Compute the distances to 0.0
                let self_diff = self.abs().to_bits().abs_diff(0);
                let other_diff = other.abs().to_bits().abs_diff(0);

                let diff = if self.is_sign_negative() == other.is_sign_negative() {
                    // If both values have the same sign, the distances to 0.0 cancel out.
                    self_diff.abs_diff(other_diff)
                } else {
                    // If the values have opposing signs, the distances to 0.0 add up.
                    match self_diff.checked_add(other_diff) {
                        Some(diff) => diff,
                        None => return false,
                    }
                };

                let Ok(diff) = u32::try_from(diff) else {
                    return false;
                };
                diff <= ulps_tolerance
            }
        }
    )+ };
}

base_impls!(f32, f64);

#[cfg(feature = "f16")]
base_impls!(f16);

#[cfg(feature = "f128")]
base_impls!(f128);

////////////////////////////////////
// Implementations for References //
////////////////////////////////////

impl<T: ApproxEq<U> + ?Sized, U: ?Sized> ApproxEq<&U> for &T {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &&U, abs_tolerance: Self::Tolerance) -> bool {
        T::abs_eq(self, *other, abs_tolerance)
    }

    fn rel_eq(&self, other: &&U, rel_tolerance: Self::Tolerance) -> bool {
        T::rel_eq(self, *other, rel_tolerance)
    }

    fn ulps_eq(&self, other: &&U, ulps_tolerance: u32) -> bool {
        T::ulps_eq(self, *other, ulps_tolerance)
    }
}

impl<T: ApproxEq<U> + ?Sized, U: ?Sized> ApproxEq<&U> for &mut T {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &&U, abs_tolerance: Self::Tolerance) -> bool {
        T::abs_eq(self, *other, abs_tolerance)
    }

    fn rel_eq(&self, other: &&U, rel_tolerance: Self::Tolerance) -> bool {
        T::rel_eq(self, *other, rel_tolerance)
    }

    fn ulps_eq(&self, other: &&U, ulps_tolerance: u32) -> bool {
        T::ulps_eq(self, *other, ulps_tolerance)
    }
}

impl<T: ApproxEq<U> + ?Sized, U: ?Sized> ApproxEq<&mut U> for &T {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &&mut U, abs_tolerance: Self::Tolerance) -> bool {
        T::abs_eq(self, *other, abs_tolerance)
    }

    fn rel_eq(&self, other: &&mut U, rel_tolerance: Self::Tolerance) -> bool {
        T::rel_eq(self, *other, rel_tolerance)
    }

    fn ulps_eq(&self, other: &&mut U, ulps_tolerance: u32) -> bool {
        T::ulps_eq(self, *other, ulps_tolerance)
    }
}

impl<T: ApproxEq<U> + ?Sized, U: ?Sized> ApproxEq<&mut U> for &mut T {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &&mut U, abs_tolerance: Self::Tolerance) -> bool {
        T::abs_eq(self, *other, abs_tolerance)
    }

    fn rel_eq(&self, other: &&mut U, rel_tolerance: Self::Tolerance) -> bool {
        T::rel_eq(self, *other, rel_tolerance)
    }

    fn ulps_eq(&self, other: &&mut U, ulps_tolerance: u32) -> bool {
        T::ulps_eq(self, *other, ulps_tolerance)
    }
}

///////////////////////////////////////////
// Implementations for Slices and Arrays //
///////////////////////////////////////////

impl<T: ApproxEq<U>, U> ApproxEq<[U]> for [T] {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &[U], abs_tolerance: Self::Tolerance) -> bool {
        if self.len() != other.len() {
            return false;
        }

        for (a, b) in self.iter().zip(other) {
            if !T::abs_eq(a, b, abs_tolerance) {
                return false;
            }
        }
        true
    }

    fn rel_eq(&self, other: &[U], rel_tolerance: Self::Tolerance) -> bool {
        if self.len() != other.len() {
            return false;
        }

        for (a, b) in self.iter().zip(other) {
            if !T::rel_eq(a, b, rel_tolerance) {
                return false;
            }
        }
        true
    }

    fn ulps_eq(&self, other: &[U], ulps_tolerance: u32) -> bool {
        if self.len() != other.len() {
            return false;
        }

        for (a, b) in self.iter().zip(other) {
            if !T::ulps_eq(a, b, ulps_tolerance) {
                return false;
            }
        }
        true
    }
}

impl<T: ApproxEq<U>, U, const N: usize> ApproxEq<&[U]> for [T; N] {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &&[U], abs_tolerance: Self::Tolerance) -> bool {
        self.as_slice().abs_eq(*other, abs_tolerance)
    }

    fn rel_eq(&self, other: &&[U], rel_tolerance: Self::Tolerance) -> bool {
        self.as_slice().rel_eq(*other, rel_tolerance)
    }

    fn ulps_eq(&self, other: &&[U], ulps_tolerance: u32) -> bool {
        self.as_slice().ulps_eq(*other, ulps_tolerance)
    }
}

impl<T: ApproxEq<U>, U, const N: usize> ApproxEq<&mut [U]> for [T; N] {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &&mut [U], abs_tolerance: Self::Tolerance) -> bool {
        self.as_slice().abs_eq(*other, abs_tolerance)
    }

    fn rel_eq(&self, other: &&mut [U], rel_tolerance: Self::Tolerance) -> bool {
        self.as_slice().rel_eq(*other, rel_tolerance)
    }

    fn ulps_eq(&self, other: &&mut [U], ulps_tolerance: u32) -> bool {
        self.as_slice().ulps_eq(*other, ulps_tolerance)
    }
}

impl<T: ApproxEq<U>, U, const N: usize> ApproxEq<[U; N]> for &[T] {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &[U; N], abs_tolerance: Self::Tolerance) -> bool {
        (**self).abs_eq(other.as_slice(), abs_tolerance)
    }

    fn rel_eq(&self, other: &[U; N], rel_tolerance: Self::Tolerance) -> bool {
        (**self).rel_eq(other.as_slice(), rel_tolerance)
    }

    fn ulps_eq(&self, other: &[U; N], ulps_tolerance: u32) -> bool {
        (**self).ulps_eq(other.as_slice(), ulps_tolerance)
    }
}

impl<T: ApproxEq<U>, U, const N: usize> ApproxEq<[U; N]> for &mut [T] {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &[U; N], abs_tolerance: Self::Tolerance) -> bool {
        (**self).abs_eq(other.as_slice(), abs_tolerance)
    }

    fn rel_eq(&self, other: &[U; N], rel_tolerance: Self::Tolerance) -> bool {
        (**self).rel_eq(other.as_slice(), rel_tolerance)
    }

    fn ulps_eq(&self, other: &[U; N], ulps_tolerance: u32) -> bool {
        (**self).ulps_eq(other.as_slice(), ulps_tolerance)
    }
}

impl<T: ApproxEq<U>, U, const N: usize> ApproxEq<[U; N]> for [T] {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &[U; N], abs_tolerance: Self::Tolerance) -> bool {
        (*self).abs_eq(other.as_slice(), abs_tolerance)
    }

    fn rel_eq(&self, other: &[U; N], rel_tolerance: Self::Tolerance) -> bool {
        (*self).rel_eq(other.as_slice(), rel_tolerance)
    }

    fn ulps_eq(&self, other: &[U; N], ulps_tolerance: u32) -> bool {
        (*self).ulps_eq(other.as_slice(), ulps_tolerance)
    }
}

impl<T: ApproxEq<U>, U, const N: usize> ApproxEq<[U; N]> for [T; N] {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &[U; N], abs_tolerance: Self::Tolerance) -> bool {
        self.as_slice().abs_eq(other.as_slice(), abs_tolerance)
    }

    fn rel_eq(&self, other: &[U; N], rel_tolerance: Self::Tolerance) -> bool {
        self.as_slice().rel_eq(other.as_slice(), rel_tolerance)
    }

    fn ulps_eq(&self, other: &[U; N], ulps_tolerance: u32) -> bool {
        self.as_slice().ulps_eq(other.as_slice(), ulps_tolerance)
    }
}

impl<T: ApproxEq<U>, U, const N: usize> ApproxEq<[U]> for [T; N] {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &[U], abs_tolerance: Self::Tolerance) -> bool {
        self.as_slice().abs_eq(other, abs_tolerance)
    }

    fn rel_eq(&self, other: &[U], rel_tolerance: Self::Tolerance) -> bool {
        self.as_slice().rel_eq(other, rel_tolerance)
    }

    fn ulps_eq(&self, other: &[U], ulps_tolerance: u32) -> bool {
        self.as_slice().ulps_eq(other, ulps_tolerance)
    }
}

////////////////////////////////
// Implementations for Tuples //
////////////////////////////////

macro_rules! last_type {
    ($a:ident,) => { $a };
    ($a:ident, $($rest_a:ident,)+) => { last_type!($($rest_a,)+) };
}

macro_rules! tuple_impls {
    ($T:ident $idx1:tt) => {
        tuple_impls!(@impl $T $idx1);
    };
    ($T:ident $idx1:tt $( $U:ident $idx2:tt )+) => {
        tuple_impls!($($U $idx2)+);
        tuple_impls!(@impl $T $idx1 $($U $idx2)+);
    };
    (@impl $($T:ident $idx:tt)+) => {
        impl<TOL: Copy, $($T: ApproxEq<Tolerance = TOL>),+> ApproxEq for ($($T,)+)
        where
            last_type!($($T,)+): ?Sized
        {
            type Tolerance = TOL;

            fn abs_eq(&self, other: &( $($T,)+ ), abs_tolerance: Self::Tolerance) -> bool {
                $( ApproxEq::abs_eq(&self.$idx, &other.$idx, abs_tolerance) )&&+
            }

            fn rel_eq(&self, other: &( $($T,)+ ), rel_tolerance: Self::Tolerance) -> bool {
                $( ApproxEq::rel_eq(&self.$idx, &other.$idx, rel_tolerance) )&&+
            }

            fn ulps_eq(&self, other: &( $($T,)+ ), ulps_tolerance: u32) -> bool {
                $( ApproxEq::ulps_eq(&self.$idx, &other.$idx, ulps_tolerance) )&&+
            }
        }
    };
}
tuple_impls!(E 11 D 10 C 9 B 8 A 7 Z 6 Y 5 X 4 W 3 V 2 U 1 T 0);

///////////////////////////////////////
// Implementations for libcore types //
///////////////////////////////////////

impl<T: ApproxEq + Copy> ApproxEq for Cell<T> {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &Cell<T>, abs_tolerance: Self::Tolerance) -> bool {
        T::abs_eq(&self.get(), &other.get(), abs_tolerance)
    }

    fn rel_eq(&self, other: &Cell<T>, rel_tolerance: Self::Tolerance) -> bool {
        T::rel_eq(&self.get(), &other.get(), rel_tolerance)
    }

    fn ulps_eq(&self, other: &Cell<T>, ulps_tolerance: u32) -> bool {
        T::ulps_eq(&self.get(), &other.get(), ulps_tolerance)
    }
}

impl<T: ApproxEq + ?Sized> ApproxEq for RefCell<T> {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &RefCell<T>, abs_tolerance: Self::Tolerance) -> bool {
        T::abs_eq(&*self.borrow(), &*other.borrow(), abs_tolerance)
    }

    fn rel_eq(&self, other: &RefCell<T>, rel_tolerance: Self::Tolerance) -> bool {
        T::rel_eq(&*self.borrow(), &*other.borrow(), rel_tolerance)
    }

    fn ulps_eq(&self, other: &RefCell<T>, ulps_tolerance: u32) -> bool {
        T::ulps_eq(&*self.borrow(), &*other.borrow(), ulps_tolerance)
    }
}

impl<T: ApproxEq> ApproxEq for Option<T> {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &Option<T>, abs_tolerance: Self::Tolerance) -> bool {
        match (self, other) {
            (Some(a), Some(b)) => T::abs_eq(a, b, abs_tolerance),
            (None, None) => true,
            _ => false,
        }
    }

    fn rel_eq(&self, other: &Option<T>, rel_tolerance: Self::Tolerance) -> bool {
        match (self, other) {
            (Some(a), Some(b)) => T::rel_eq(a, b, rel_tolerance),
            (None, None) => true,
            _ => false,
        }
    }

    fn ulps_eq(&self, other: &Option<T>, ulps_tolerance: u32) -> bool {
        match (self, other) {
            (Some(a), Some(b)) => T::ulps_eq(a, b, ulps_tolerance),
            (None, None) => true,
            _ => false,
        }
    }
}

impl<T: ApproxEq> ApproxEq for OnceCell<T> {
    type Tolerance = T::Tolerance;

    fn abs_eq(&self, other: &Self, abs_tolerance: Self::Tolerance) -> bool {
        self.get().abs_eq(&other.get(), abs_tolerance)
    }

    fn rel_eq(&self, other: &Self, rel_tolerance: Self::Tolerance) -> bool {
        self.get().rel_eq(&other.get(), rel_tolerance)
    }

    fn ulps_eq(&self, other: &Self, ulps_tolerance: u32) -> bool {
        self.get().ulps_eq(&other.get(), ulps_tolerance)
    }
}

#[cfg(test)]
mod tests {
    use crate::{assert_approx_eq, assert_approx_ne};

    #[test]
    fn option() {
        assert_approx_eq!(None::<f32>, None::<f32>).abs(0.0);
        assert_approx_eq!(None::<f32>, None::<f32>).rel(0.0);
        assert_approx_eq!(None::<f32>, None::<f32>).ulps(0);
        assert_approx_eq!(Some(0.0), Some(0.0)).abs(0.0);
        assert_approx_eq!(Some(0.0), Some(0.0)).rel(0.0);
        assert_approx_eq!(Some(0.0), Some(0.0)).ulps(0);

        assert_approx_ne!(None::<f32>, Some(0.0)).rel(0.0);
        assert_approx_ne!(Some(0.0), None::<f32>).rel(0.0);
    }

    #[test]
    fn slice() {
        assert_approx_eq!(&[0.0][..], &[0.0][..]);
        assert_approx_ne!(&[0.0][..], &[0.0, 0.0][..]);
        assert_approx_ne!(&[0.0, 0.0][..], &[0.0][..]);
    }
}