-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsqrt_test.go
More file actions
52 lines (42 loc) · 953 Bytes
/
sqrt_test.go
File metadata and controls
52 lines (42 loc) · 953 Bytes
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
package exact_test
import (
"math"
"testing"
"github.com/madlambda/exact"
)
func almostFloat(x, y, ε float64) bool {
return math.Abs(x-y) <= ε
}
func assert(t *testing.T, b bool, msg string) {
t.Helper()
if !b {
t.Fatal(msg)
}
}
func assertAlmost(t *testing.T, x, y, ε float64, msg string) {
t.Helper()
assert(t, almostFloat(x, y, ε), fmt("Fail: %s. Differs: %.12f != %.12f",
msg, x, y))
}
func TestRatSqrtAgainstFloat(t *testing.T) {
for i := uint64(0); i < 1000; i++ {
fp := float64(i)
frac := exact.NewRat(i, 1)
sfp := math.Sqrt(fp)
sf := exact.Sqrt(frac)
assertAlmost(t, sfp, sf.Inexact(),
exact.DefPrecision.Inexact(), fmt("sqrt(%d)", i))
}
}
func BenchmarkExactSqrt2(b *testing.B) {
two := exact.NewRat(2, 1)
for n := 0; n < b.N; n++ {
exact.Sqrt(two)
}
}
func BenchmarkMathSqrt2(b *testing.B) {
// unfair comparison, but nice to see the difference
for n := 0; n < b.N; n++ {
math.Sqrt(2.0)
}
}