def f(x):
return x*x-4*x+5
a0,b0=1,3
1、均匀搜索
令
δ
=
(
b
0
−
a
0
)
/
N
,
a
i
=
a
0
+
i
δ
,
i
=
1
,
2
,
3
\delta=(b_0-a_0)/N,a_i=a_0+i\delta,i=1,2,3
δ=(b0−a0)/N,ai=a0+iδ,i=1,2,3
while b0-a0>0.1:
a=np.linspace(a0,b0,5)
for i in range(1,4):
if f(a[i-1])>f(a[i]) and f(a[i+1])>f(a[i]):
a0,b0=a[i-1],a[i+1]
break
print((a0+b0)/2)
极小点为2
2、黄金区间法
令
τ
=
(
5
−
1
)
/
2
,
λ
=
a
0
+
(
1
−
τ
)
(
b
0
−
a
0
)
,
μ
=
a
0
+
τ
(
b
0
−
a
0
)
\tau=(\sqrt{5}-1)/2,\lambda=a_0+( 1-\tau)(b_0-a_0),\mu=a_0+\tau(b_0-a_0)
τ=(5−1)/2,λ=a0+(1−τ)(b0−a0),μ=a0+τ(b0−a0)
tao=(pow(5,0.5)-1)/2
lamda=a0+(1-tao)*(b0-a0)
miu=a0+tao*(b0-a0)
while miu-lamda>0.1:
if f(lamda)<f(miu):
b0=miu
else:
a0=lamda
lamda=a0+(1-tao)*(b0-a0)
miu=a0+tao*(b0-a0)
print((lamda+miu)/2)
极小点约等于2.09
3、导数二分法
记区间中点
λ
=
(
a
0
+
b
0
)
/
2
\lambda=(a_0+b_0)/2
λ=(a0+b0)/2
def first_order(x):
return 2*x-4
while True:
lamda=(a0+b0)/2
value=first_order(lamda)
if value==0:
print(lamda)
break
elif value<0:
a0=lamda
else:
b0=lamda
极小点为2