1def ternary_search(f, left, right, absolute_precision) -> float:
2 """Find maximum of unimodal function f() within [left, right]
3 To find the minimum, reverse the if/else statement or reverse the comparison.
4 """
5 while abs(right - left) >= absolute_precision:
6 left_third = left + (right - left) / 3
7 right_third = right - (right - left) / 3
8
9 if f(left_third) < f(right_third):
10 left = left_third
11 else:
12 right = right_third
13
14 # Left and right are the current bounds; the maximum is between them
15 return (left + right) / 2
16