-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy path11-01_sqrt_test.go
56 lines (50 loc) · 1.06 KB
/
11-01_sqrt_test.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
package hd_test
import (
"math"
"math/rand/v2"
"testing"
hd "github.com/nikolaydubina/go-hackers-delight"
)
func sqrtBasicFloat64(x uint32) uint32 { return uint32(math.Floor(math.Sqrt(float64(x)))) }
func FuzzSqrt(f *testing.F) {
for _, u := range fuzzUint32 {
f.Add(u)
}
f.Fuzz(func(t *testing.T, x uint32) {
exp := sqrtBasicFloat64(x)
got := [...]uint32{
hd.SqrtNewton(x),
hd.SqrtBinarySearch(x),
hd.SqrtShiftAndSubtract(x),
}
for i, q := range got {
if exp != q {
t.Errorf("%d: exp(%v) q(%v) x(%x)", i, exp, q, x)
}
}
})
}
func BenchmarkSqrt(b *testing.B) {
var vals []uint32
for i := 0; i < 10000; i++ {
vals = append(vals, rand.Uint32())
}
vs := []struct {
name string
f func(x uint32) uint32
}{
{"basic", sqrtBasicFloat64},
{"SqrtNewton", hd.SqrtNewton},
{"SqrtBinarySearch", hd.SqrtBinarySearch},
{"SqrtShiftAndSubtract", hd.SqrtShiftAndSubtract},
}
for _, v := range vs {
b.Run(v.name, func(b *testing.B) {
for b.Loop() {
for j := 0; j < len(vals)-1; j++ {
v.f(vals[j])
}
}
})
}
}