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)
| 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. |
| 27 | func 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 | } |
no outgoing calls