写在前面的话:咋们还是用scipy.optimize吧
例函数:y=0.5x2−20x+1y=0.5x^{2}-20x +1y=0.5x2−20x+1
求该函数在(0, 100)的最小值.
模拟退火(SA)程序,如下:
import math
import numpy as np
def x_y(x):
return 0.5*x**2 - 20*x + 1
T = 100
T_min = 0.5
x = np.random.uniform(0, 100)
y = 0
t = 0
k = 50
#start = time.clock()
while T > T_min:
for j in range(k):
y = x_y(x)
x_new = x + np.random.uniform(-0.075, 0.075)*T
if (0 <= x_new and x_new <= 100):
y_new = x_y(x_new)
if y_new < y:
x = x_new
else:
pt = math.exp(-(abs(y_new-y))/T)
r = np.random.uniform(0, 1)
if r < pt:
x = x_new
t = t + 1
T = 100*0.95**t
#end = time.clock()
#print(end - start)
print(x)
print(x_y(x))
结果:
1.
x的值: 19.32899532568824
y的值: -198.7748763635259
2.
x的值: 19.801049478792827
y的值: -198.98020934505573
3.
x的值: 20.955862513214015
y的值: -198.54316342791608
得到的解一直在x=20x=20x=20左右摆动.
可增加迭代次数kkk让程序更精确或调低最低温度
(也可能是笔者调参不当,愿指教)
增加迭代次数k=200k=200k=200后的解,
1.
x的值: 19.677463415583063
y的值: -198.94798507585634
2.
x的值: 20.459547736489352
y的值: -198.89440793894377
3.
x的值: 20.778061032165297
y的值: -198.69731051511295
比较:
scipy.optimize
from scipy.optimize import minimize
fun = lambda x: 0.5*x[0]**2 - 20*x[0] + 1
bnds = [(0, 100)]
res = minimize(fun, (2.0), method='SLSQP', bounds=bnds)
print(res.x)
结果:
[20.]
t4ngw
原创文章 32获赞 49访问量 1万+
关注
私信
展开阅读全文