Approximate equality for floats can be handled by defining a custom comparer on floats that determines two values to be equal if they are within some range of each other. This example is for demonstrative purposes; use [github.com/google/go-cmp/cmp/cmpopts.EquateApprox] instead.
()
| 64 | // This example is for demonstrative purposes; |
| 65 | // use [github.com/google/go-cmp/cmp/cmpopts.EquateApprox] instead. |
| 66 | func ExampleOption_approximateFloats() { |
| 67 | // This Comparer only operates on float64. |
| 68 | // To handle float32s, either define a similar function for that type |
| 69 | // or use a Transformer to convert float32s into float64s. |
| 70 | opt := cmp.Comparer(func(x, y float64) bool { |
| 71 | delta := math.Abs(x - y) |
| 72 | mean := math.Abs(x+y) / 2.0 |
| 73 | return delta/mean < 0.00001 |
| 74 | }) |
| 75 | |
| 76 | x := []float64{1.0, 1.1, 1.2, math.Pi} |
| 77 | y := []float64{1.0, 1.1, 1.2, 3.14159265359} // Accurate enough to Pi |
| 78 | z := []float64{1.0, 1.1, 1.2, 3.1415} // Diverges too far from Pi |
| 79 | |
| 80 | fmt.Println(cmp.Equal(x, y, opt)) |
| 81 | fmt.Println(cmp.Equal(y, z, opt)) |
| 82 | fmt.Println(cmp.Equal(z, x, opt)) |
| 83 | |
| 84 | // Output: |
| 85 | // true |
| 86 | // false |
| 87 | // false |
| 88 | } |
| 89 | |
| 90 | // Normal floating-point arithmetic defines == to be false when comparing |
| 91 | // NaN with itself. In certain cases, this is not the desired property. |