-
Notifications
You must be signed in to change notification settings - Fork 1
/
equal.go
63 lines (57 loc) · 1.46 KB
/
equal.go
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
package floats
import (
"math"
)
var (
// MinNormal is the smallest positive normal value of type float64.
MinNormal = math.Float64frombits(0x0010000000000000)
// MinNormal32 is the smallest positive normal value of type float32.
MinNormal32 = math.Float32frombits(0x00800000)
)
// AlmostEqual returns true if a and b are equal within a relative error of
// ε. See http://floating-point-gui.de/errors/comparison/ for the details of the
// applied method.
func AlmostEqual(a, b, ε float64) bool {
if a == b {
return true
}
absA := math.Abs(a)
absB := math.Abs(b)
diff := math.Abs(a - b)
if a == 0 || b == 0 || absA+absB < MinNormal {
return diff < ε*MinNormal
}
return diff/math.Min(absA+absB, math.MaxFloat64) < ε
}
// AlmostEqual32 returns true if a and b are equal within a relative error of
// ε. See http://floating-point-gui.de/errors/comparison/ for the details of the
// applied method.
func AlmostEqual32(a, b, ε float32) bool {
if a == b {
return true
}
absA := Abs32(a)
absB := Abs32(b)
diff := Abs32(a - b)
if a == 0 || b == 0 || absA+absB < MinNormal32 {
return diff < ε*MinNormal32
}
return diff/Min32(absA+absB, math.MaxFloat32) < ε
}
// Abs32 works like math.Abs, but for float32.
func Abs32(x float32) float32 {
switch {
case x < 0:
return -x
case x == 0:
return 0 // return correctly abs(-0)
}
return x
}
// Min32 works like math.Min, but for float32.
func Min32(x, y float32) float32 {
if x < y {
return x
}
return y
}