ternarySearch

inline fun ternarySearch(left: Double, right: Double, f: (Double) -> Double): Double(source)

Returns an approximation of the argument in [left, right] at which f is greatest. f must be unimodal: strictly increasing, then strictly decreasing. The interval is narrowed to 1e-9, or to two adjacent doubles where they are more than 1e-9 apart. Near a smooth maximum the values of f can round to equal doubles, and the result is then less accurate: for x * (20 - x) on 0..20 it is off by about 1e-7, and a large constant added to f makes it worse.

Throws

Samples

val x = ternarySearch(0.0, 10.0) { x -> -(x - 3) * (x - 3) + 9 }

assertEquals(3.0, x, absoluteTolerance = 1e-6)
// To find a minimum, maximize the negated function: (x - 4)^2 + 1 is smallest at x = 4
val x = ternarySearch(0.0, 10.0) { x -> -((x - 4) * (x - 4) + 1) }

assertEquals(4.0, x, absoluteTolerance = 1e-6)