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
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
//! Approximate equality.
//!
//! This crate provides mechanisms for comparing floating-point numbers and structures containing
//! floating-point numbers for *approximate equality* in the presence of rounding and measurement
//! errors.
//!
//! # Comparisons
//!
//! The [`approx_eq`] function can be used to compare two values for *approximate equality*.
//!
//! [`approx_eq`] returns a [`Comparison`], which has to be dereferenced to obtain the comparison
//! result as a [`bool`]. It can also be inverted to get the inverted result.
//!
//! ```
//! use ballpark::approx_eq;
//!
//! if !approx_eq(1.0, 1.0 + f64::EPSILON) {
//! panic!("these are only a single `f64` apart, so they should be approximately equal");
//! }
//! if *approx_eq(10.0, 11.0) {
//! panic!("10 and 11 are pretty far apart, so they should not be considered equal");
//! }
//! ```
//!
//! [`Comparison`] allows configuring the specific type of comparison and tolerance threshold with
//! the [`Comparison::abs`], [`Comparison::rel`], and [`Comparison::ulps`] methods.
//!
//! If none of these methods are used to customize the comparison, a *default comparison* is
//! performed, which is a [`Comparison::ulps`] comparison with a tolerance of 4 ULPs.
//!
//! # Assertions
//!
//! One of the most common use cases of this crate is to assert that two values are *almost equal*,
//! up to some tolerance value.
//! This can be done via the [`assert_approx_eq!`] and [`assert_approx_ne!`] macros, which work
//! similarly to [`assert_eq!`] and [`assert_ne!`], respectively.
//!
//! ```
//! use ballpark::assert_approx_eq;
//!
//! // Basic usage:
//! let a = 10.0;
//! let b = 1.0 / (1.0 / a);
//! assert_approx_eq!(a, b);
//!
//! // Like `assert_eq!`, it supports a custom panic message:
//! assert_approx_eq!(a, b, "inverting {} twice should give the same result", a);
//! ```
//!
//! Unlike [`assert_eq!`] and [`assert_ne!`], which evaluate to `()`, the assertion macros in
//! *ballpark* return an [`Assertion`] object that can be used to set custom comparison thresholds:
//!
//! ```
//! use ballpark::{assert_approx_eq, assert_approx_ne};
//!
//! // These values are too far away for the default comparison to consider them equal:
//! let a = 10.0;
//! let b = 10.1;
//!
//! assert_approx_ne!(a, b);
//!
//! // The values are less than 0.25 apart, so an *absolute difference* comparison with a tolerance
//! // of 0.25 will treat them as equal:
//! assert_approx_eq!(a, b).abs(0.25);
//!
//! // They are also within 1% of each other, so a relative comparison with a tolerance of 0.01
//! // also treats them as equal:
//! assert_approx_eq!(a, b).rel(0.01);
//! ```
//!
//! # Custom Types
//!
//! User-defined types can implement the [`ApproxEq`] trait to become compatible with this crate.
//! All methods of [`ApproxEq`] should forward the operation to all contained fields that
//! contribute to a type's [`PartialEq`] result and `&&` the results.
//!
//! ```
//! use ballpark::ApproxEq;
//!
//! pub struct Vec2<T> {
//! x: T,
//! y: T,
//! }
//!
//! impl<T: ApproxEq> ApproxEq for Vec2<T> {
//! type Tolerance = T::Tolerance;
//!
//! fn abs_eq(&self, other: &Self, abs_tolerance: Self::Tolerance) -> bool {
//! self.x.abs_eq(&other.x, abs_tolerance) &&
//! self.y.abs_eq(&other.y, abs_tolerance)
//! }
//!
//! fn rel_eq(&self, other: &Self, rel_tolerance: Self::Tolerance) -> bool {
//! self.x.rel_eq(&other.x, rel_tolerance) &&
//! self.y.rel_eq(&other.y, rel_tolerance)
//! }
//!
//! fn ulps_eq(&self, other: &Self, ulps_tolerance: u32) -> bool {
//! self.x.ulps_eq(&other.x, ulps_tolerance) &&
//! self.y.ulps_eq(&other.y, ulps_tolerance)
//! }
//! }
//! ```
//!
//! # Cargo Features
//!
//! This library exposes the following Cargo features:
//!
//! * **`std`** (enabled by default): implements [`ApproxEq`] for some types in `libstd`.
//! * **`alloc`** (enabled by default): implements [`ApproxEq`] for data structures and collections
//! from the `alloc` crate.
//! * **`f16`**: implements [`ApproxEq`] for Rust's unstable [`f16`] type. Requires a nightly
//! compiler.
//! * **`f128`**: implements [`ApproxEq`] for Rust's unstable [`f128`] type. Requires a nightly
//! compiler.
//!
//! Turning off the **`std`** feature makes this library `#![no_std]`, and with **`alloc`** also
//! turned off, it becomes usable in environments that don't have a `#[global_allocator]`.
/// ```
/// use ballpark::*;
/// assert_approx_eq!(1.0, 1.0);
/// ```
///
/// Assertions borrow a temporary to prevent storage in locals.
///
/// ```compile_fail
/// use ballpark::*;
/// let assertion = assert_approx_eq!(1.0, 1.0);
/// ```
///
/// This is just a minor obstable – they can still be passed as arguments – but makes it harder to
/// get into a situation of potentially panicking in `Drop` when another `Assertion` is already
/// unwinding.
/// If the `std` feature is disabled, `thread::panicking` is unavailable, so we cannot prevent the
/// double-panic.
use ;
/// Implementation details used by macros. Semver-exempt. Do not use.
/// Types that can be compared for *approximate equality*.
///
/// Compound types implementing this trait are considered *equal* if all of their fields are.
///
/// # Implementing
///
/// [`ApproxEq`] can be implemented for custom data structures by simply forwarding to the
/// implementation of all the constituent types, similar to how [`PartialEq`] would be implemented.
/// However, it does not support structures that mix different primitive types like [`f32`] and
/// [`f64`].
/// Tolerance in ULPs used by the *default comparison*.
///
/// The same value is used for all floating-point types, since the accuracy of computations is
/// nearly always constant when measured in ULPs, no matter what floating-point type ([`f32`] or
/// [`f64`]) is used.
const DEFAULT_TOLERANCE_ULPS: u32 = 4;
/// Compares two values using approximate equality.
///
/// Returns a [`Comparison`], which allows specifying the tolerance values to use and the exact type
/// of comparison to perform.
/// [`Comparison`] can either be dereferenced (`*`) to obtain its result as a [`bool`], or inverted
/// (`!`) to get the negated result.
///
/// If none of [`Comparison::abs`], [`Comparison::rel`] or [`Comparison::ulps`] is called to request
/// a specific type of comparison, a *default comparison* is performed.
/// This *default comparison* is a [`Comparison::ulps`] comparison with a tolerance of 4 ULPs.
///
/// If more than one comparison is requested, the values will be considered equal if *any*
/// comparison considers them equal (ie. the results are ORed together).
///
/// # Examples
///
/// Basic usage:
///
/// ```
/// # use ballpark::*;
/// # let input = 0.0;
/// if *approx_eq(input, 0.0) {
/// println!("roughly nothing!");
/// }
/// if !approx_eq(input, 0.0) {
/// println!("roughly something!");
/// }
/// ```
///
/// Custom tolerance:
///
/// ```
/// # use ballpark::*;
/// if *approx_eq(10.0, 10.5).abs(0.6) {
/// println!(r"close enough ¯\_(ツ)_/¯");
/// }
/// ```
/// Comparator for approximate equality of values.
///
/// Returned by the [`approx_eq`] function.
///
/// This type can be dereferenced with `*comp` to obtain the result of the comparison. It can also
/// be negated via `!comp` to obtain the negated result.
///
/// If no method is called to configure the specific type of comparison to perform, a *default
/// comparison* will be performed.
/// This *default comparison* is a [`Comparison::ulps`] comparison with a tolerance of 4 ULPs.
/// [`Comparison`] can be inverted to get the opposite result compared to deferencing.
/// Assertion guard returned by [`assert_approx_eq!`][crate::assert_approx_eq]
/// and [`assert_approx_ne!`][crate::assert_approx_ne].
///
/// This type will check the assertion when dropped, and has methods that allow configuring the
/// comparison method and tolerances to use. It supports 3 ways of comparing values that can be
/// enabled by calling the appropriate methods:
///
/// - [`Assertion::abs`] for comparing the value's *absolute difference* via
/// [`ApproxEq::abs_eq`].
/// - [`Assertion::rel`] for comparing the value's *relative difference* via
/// [`ApproxEq::rel_eq`].
/// - [`Assertion::ulps`] for comparing the values by checking how many other values can fit between
/// them via [`ApproxEq::ulps_eq`].
///
/// If more than one of these methods is called, the values will be considered equal if *any*
/// comparison considers them equal (ie. the results are ORed together).
///
/// # Panics in [`Drop`] and `#![no_std]`
///
/// If a thread is panicking, and another panic happens in a [`Drop`] implementation, the process
/// will be terminated.
///
/// To prevent this, the [`Drop`] implementation of [`Assertion`] will check
/// [`thread::panicking`][::std::thread::panicking] to see if the thread is currently unwinding,
/// but **only if the `std` feature is enabled**, since Rust offers no way to detect whether this
/// symbol is available otherwise.
///
/// Note that this is not really a problem when this library is used properly:
/// When there is a simple sequence of [`assert_approx_eq!`] family macro invocations, there will
/// only ever be a single [`Assertion`] object that gets constructed, checked, and discarded before
/// the next one is created.
///
/// Therefore, it is best to follow a few simple rules: Don't store [`Assertion`]s in local
/// variables, don't pass them as arguments, and don't put them in compound types like `struct`s or
/// tuples.
///
/// These consideration do not apply to [`Comparison`], since that does not have a destructor.
!
/// Asserts that two expressions are approximately equal to each other (using [`ApproxEq`]).
///
/// This macro functions identically to [`assert_eq!`], except in that it uses the [`ApproxEq`]
/// trait to perform an approximate comparison.
///
/// The macro expands to an expression that evaluates to an [`Assertion`] object that can be used to
/// configure the exact type of comparison, as well as the tolerance values to use:
///
/// - [`Assertion::abs`] compares the value's *absolute difference* via [`ApproxEq::abs_eq`].
/// - [`Assertion::rel`] compares the value's *relative difference* via [`ApproxEq::rel_eq`].
/// - [`Assertion::ulps`] compares the values by checking how many other values can fit between
/// them via [`ApproxEq::ulps_eq`].
///
/// Also see [`assert_approx_ne!`][crate::assert_approx_ne].
///
/// # Examples
///
/// Default approximate comparison:
///
/// ```
/// # use ballpark::*;
/// let one = (0..10).fold(0.0, |acc, _| acc + 0.1);
/// assert_approx_eq!(one, 1.0);
/// ```
///
/// Perform absolute and relative comparisons with custom tolerance values:
///
/// ```
/// # use ballpark::*;
/// assert_approx_eq!(100.0, 99.0).abs(1.0);
/// assert_approx_eq!(100.0, 99.0).rel(0.01);
/// ```
///
/// Compare values via ULPs, based on the number of floats that fit between them:
///
/// ```
/// # use ballpark::*;
/// assert_approx_eq!(1.0, 1.0 + f64::EPSILON).ulps(1);
/// ```
/// Asserts that two expressions are *not* approximately equal to each other (using [`ApproxEq`]).
///
/// This macro functions identically to [`assert_ne!`], except in that it uses the [`ApproxEq`]
/// trait to perform an approximate comparison, and returns an [`Assertion`] that can be used to
/// configure the exact type of comparison, as well as the tolerance values to use.
///
/// Also see [`assert_approx_eq!`].
///
/// # Examples
///
/// Perform absolute and relative comparisons with custom tolerance values:
///
/// ```
/// # use ballpark::*;
/// assert_approx_ne!(100.0, 99.0).abs(0.5);
/// assert_approx_ne!(100.0, 99.0).rel(0.005);
/// ```
///
/// Compare values via ULPs, based on the number of floats that fit between them:
///
/// ```
/// # use ballpark::*;
/// assert_approx_ne!(1.0, 1.0 + f64::EPSILON + f64::EPSILON).ulps(1);
/// ```
/// Debug-asserts that two expressions are approximately equal to each other.
///
/// This macro functions identically to [`assert_approx_eq!`], except the assertion is only checked
/// when debug assertions are enabled.
/// Debug-asserts that two expressions are *not* approximately equal to each other.
///
/// This macro functions identically to [`assert_approx_ne!`], except the assertion is only checked
/// when debug assertions are enabled.