MCPcopy Create free account
hub / github.com/TheAlgorithms/Go / TernaryMin

Function TernaryMin

search/ternary.go:27–40  ·  view source on GitHub ↗

TernaryMin is a function to search for minimum value of a uni-modal function `f` in the interval [a, b]. a and b should be finit numbers.

(a, b, epsilon float64, f func(x float64) float64)

Source from the content-addressed store, hash-verified

25// TernaryMin is a function to search for minimum value of a uni-modal function `f`
26// in the interval [a, b]. a and b should be finit numbers.
27func TernaryMin(a, b, epsilon float64, f func(x float64) float64) (float64, error) {
28 if a == math.Inf(-1) || b == math.Inf(1) {
29 return -1, fmt.Errorf("interval boundaries should be finite numbers")
30 }
31 if math.Abs(a-b) <= epsilon {
32 return f((a + b) / 2), nil
33 }
34 left := (2*a + b) / 3
35 right := (a + 2*b) / 3
36 if f(left) > f(right) {
37 return TernaryMin(left, b, epsilon, f)
38 }
39 return TernaryMin(a, right, epsilon, f)
40}

Callers 1

TestTernaryMinFunction · 0.85

Calls

no outgoing calls

Tested by 1

TestTernaryMinFunction · 0.68