模拟退火流程图
import matplotlib.pyplot as plt
import numpy as np
import math
#设置函数
def aimFunction(x):
y = x**3-60*x**2-4*x+6
return y
x = [i/10 for i in range(1000)]
y = [0 for i in range(1000)]
y_min = 0
for i in range(1000):
y[i] = aimFunction(x[i])
if y_min > y[i]:
y_min = y[i]
x_min = x[i]
print(x_min)
plt.plot(x,y)
plt.scatter(x_min,y_min,c='red',edgecolors='none',s=100)
plt.show()
#模拟退火
#设置初始温度
T = 1000
#设置最小温度
Tmin = 100
#内循环次数
k = 50
#初始值
x = 0
t = 0
while T >= Tmin:
for i in range(k):
y = aimFunction(x)
#选择邻域值
xNew = x + np.random.uniform(low=-0.055, high=0.055) * T
if (xNew>=0 and xNew<=100):
yNew = aimFunction(xNew)
if yNew-y<0:
x = xNew
else:
#metropolis准则
p = math.exp(-(yNew - y) / T)
r = np.random.uniform(low=0, high=1)
if r < p:
x = xNew
t+=1
#降温函数
T=1000/(1+t)
print(x)
输出结果
40.0
40.07088608817078
通过比较得知模拟退火得到的最优解达到了良好的逼近效果
此程序参考https://blog.csdn.net/wfrainn/article/details/80303138