python代码实现求解最值问题的模拟退火
程序员文章站
2023-12-12 16:44:46
基于python求解一元最值问题的模拟退火给出一元最值问题的模拟退火python代码,多元最值问题适当修改即可:问题描述:求解函数y=11sin(x)+7cos(5x)在[-3,3]内的最大值!# --utf-8--# author: 来瓶安慕嘻# time:2020-7-2# 模拟退火import pandas as pdfrom matplotlib import pyplot as pltimport numpy as npimport mathimport randomd...
基于python求解一元最值问题的模拟退火
给出一元最值问题的模拟退火python代码,多元最值问题适当修改即可:
问题描述:求解函数y=11sin(x)+7cos(5x)在[-3,3]内的最大值!
# --utf-8--
# author: 来瓶安慕嘻
# time:2020-7-2
# 模拟退火
import pandas as pd
from matplotlib import pyplot as plt
import numpy as np
import math
import random
def sa():
'''初始化参数'''
T0 = 100
T = T0
maxgen = 300
Lk = 100
alfa = 0.95
x_lb = -3
x_ub = 3
'''初始化x0,y0'''
x0 = x_lb+(x_ub-x_lb)*random.random()
# 初始化iter_x和iter_y,用来储存每一次的y值和x值,用来最后搜寻最大值和最小值
iter_x = [x0]
iter_y = [cal_y(x0)]
'''==========================
开始模拟退火啦
=============================
'''
for i in range(maxgen):
for j in range(Lk):
y0 = cal_y(x0)
y = np.random.randn(1)
x_new = x0+y*T
if x_new < x_lb:
r = random.random()
x_new= r*x_lb+(1-r)*x0
elif x_new > x_ub:
r = random.random()
x_new= r*x_ub+(1-r)*x0
x1 = x_new
y1 = cal_y(x1)
if y1>y0:
x0 = x1
iter_x.append(x1)
iter_y.append(y1)
else:
p = math.exp(-(y0-y1)/T)
if random.random() < p:
x0 = x1
T = alfa*T
best_y = max(iter_y)
best_x = float(iter_x[iter_y.index(best_y)])
print('最佳的位置为:',np.round(best_x,4))
print('对应的最优值为:',np.round(best_y,4))
def cal_y(x):
y = 11 * math.sin(x) + 7 * math.cos(5 * x)
return y
if __name__ == '__main__':
sa()
本文地址:https://blog.csdn.net/stephen_curry300/article/details/107092190