-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmath_test.go
More file actions
71 lines (60 loc) · 1.2 KB
/
math_test.go
File metadata and controls
71 lines (60 loc) · 1.2 KB
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
package g
import (
"math"
"math/rand"
"testing"
)
func absBits(v float32) float32 {
return math.Float32frombits(math.Float32bits(v) &^ (1 << 31))
}
func absComp(v float32) float32 {
if v < 0 {
return -v
}
return v
}
func TestAbs(t *testing.T) {
errcount := 0
for i := 0; i < 10000; i++ {
v := rand.Float32()*1e6 - 1e6/2
bits := absBits(v)
comp := absComp(v)
if bits != comp {
t.Errorf("different result %v: %v %v", v, bits, comp)
errcount++
if errcount >= 10 {
t.Fail()
}
}
}
}
const numberCount = 1024
var numbers = make([]float32, numberCount)
var positive = make([]float32, numberCount)
func init() {
for i := range numbers {
numbers[i] = rand.Float32()*1e6 - 1e6/2
positive[i] = rand.Float32() * 1e6
}
numbers[0] = 0
}
func BenchmarkAbsBits(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = absBits(numbers[i%numberCount])
}
}
func BenchmarkAbsComp(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = absComp(numbers[i%numberCount])
}
}
func BenchmarkAbsBitsPositive(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = absBits(positive[i%numberCount])
}
}
func BenchmarkAbsCompPositive(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = absComp(positive[i%numberCount])
}
}