-
Notifications
You must be signed in to change notification settings - Fork 31
/
三分法求凸函数极值.py
62 lines (46 loc) · 1.68 KB
/
三分法求凸函数极值.py
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
57
58
59
60
61
62
"""
三分法求单峰函数的极值点.
更快的版本见: FibonacciSearch
"""
from typing import Callable
INF = int(4e18)
def minimize(fun: Callable[[int], int], left: int, right: int) -> int:
"""三分法求`严格凸函数fun`在`[left,right]`间的最小值"""
res = INF
while (right - left) >= 3:
diff = (right - left) // 3
mid1 = left + diff
mid2 = right - diff
if fun(mid1) > fun(mid2):
left = mid1
else:
right = mid2
while left <= right:
cand = fun(left)
res = cand if cand < res else res
left += 1
return res
def maximize(fun: Callable[[int], int], left: int, right: int) -> int:
"""三分法求`严格凸函数fun`在`[left,right]`间的最大值"""
res = -INF
while (right - left) >= 3:
diff = (right - left) // 3
mid1 = left + diff
mid2 = right - diff
if fun(mid1) < fun(mid2):
left = mid1
else:
right = mid2
while left <= right:
cand = fun(left)
res = cand if cand > res else res
left += 1
return res
def optimize(fun: Callable[[int], int], left: int, right: int, *, min: bool) -> int:
"""三分法求`严格凸函数fun`在`[left,right]`间的最值"""
return minimize(fun, left, right) if min else maximize(fun, left, right)
if __name__ == "__main__":
assert optimize(lambda x: x**2 + 2 * x, -1, 400, min=True) == -1
assert optimize(lambda x: 0, -1, 400, min=True) == 0
assert optimize(lambda x: x**2, -1, 40, min=False) == 1600
assert optimize(lambda x: x**2, -50, 40, min=False) == 2500