forked from TheAlgorithms/Go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ternary_test.go
56 lines (49 loc) · 1.29 KB
/
ternary_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 search
import (
"math"
"testing"
)
const EPS = 1e-6
func equal(a, b float64) bool {
return math.Abs(a-b) <= EPS
}
func TestTernaryMax(t *testing.T) {
var tests = []struct {
f func(x float64) float64
a float64
b float64
expected float64
}{
{f: func(x float64) float64 { return -x * x }, a: 1, b: -1, expected: 0},
{f: func(x float64) float64 { return -2*x*x - x + 1 }, a: -1, b: 1, expected: 1.125},
}
for _, test := range tests {
result, err := TernaryMax(test.a, test.b, EPS, test.f)
if err != nil {
t.Errorf("error occurred: %v", err)
}
if !equal(result, test.expected) {
t.Errorf("Wrong result! Expected:%v, returned:%v ", test.expected, result)
}
}
}
func TestTernaryMin(t *testing.T) {
var tests = []struct {
f func(x float64) float64
a float64
b float64
expected float64
}{
{f: func(x float64) float64 { return x * x }, a: -1, b: 1, expected: 0},
{f: func(x float64) float64 { return 2*x*x + x + 1 }, a: -1, b: 1, expected: 0.875},
}
for _, test := range tests {
result, err := TernaryMin(test.a, test.b, EPS, test.f)
if err != nil {
t.Errorf("error occurred: %v", err)
}
if !equal(result, test.expected) {
t.Errorf("Wrong result! Expected:%v, returned:%v ", test.expected, result)
}
}
}