MCPcopy
hub / github.com/google/go-cmp / ExampleOption_equalNaNs

Function ExampleOption_equalNaNs

cmp/example_test.go:95–115  ·  view source on GitHub ↗

Normal floating-point arithmetic defines == to be false when comparing NaN with itself. In certain cases, this is not the desired property. This example is for demonstrative purposes; use [github.com/google/go-cmp/cmp/cmpopts.EquateNaNs] instead.

()

Source from the content-addressed store, hash-verified

93// This example is for demonstrative purposes;
94// use [github.com/google/go-cmp/cmp/cmpopts.EquateNaNs] instead.
95func ExampleOption_equalNaNs() {
96 // This Comparer only operates on float64.
97 // To handle float32s, either define a similar function for that type
98 // or use a Transformer to convert float32s into float64s.
99 opt := cmp.Comparer(func(x, y float64) bool {
100 return (math.IsNaN(x) && math.IsNaN(y)) || x == y
101 })
102
103 x := []float64{1.0, math.NaN(), math.E, 0.0}
104 y := []float64{1.0, math.NaN(), math.E, 0.0}
105 z := []float64{1.0, math.NaN(), math.Pi, 0.0} // Pi constant instead of E
106
107 fmt.Println(cmp.Equal(x, y, opt))
108 fmt.Println(cmp.Equal(y, z, opt))
109 fmt.Println(cmp.Equal(z, x, opt))
110
111 // Output:
112 // true
113 // false
114 // false
115}
116
117// To have floating-point comparisons combine both properties of NaN being
118// equal to itself and also approximate equality of values, filters are needed

Callers

nothing calls this directly

Calls 2

ComparerFunction · 0.92
EqualFunction · 0.92

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…