单起点,有时还是会落在局部最小值点
import random
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
'''
没有拜托局限性,要在随机时开始循环,每次结果进行比较找到全局最优解
'''
def inputfun(x1, x2):
return (x1 - 2) * (x1 + 3) * (x1 + 8) * (x1 - 9)*(x2 - 2) * (x2 + 3) * (x2 + 8) * (x2 - 9)
initT = 1000 # 初始温度
minT = 1 # 温度下限
iterL = 500 # 每个T值的迭代次数
delta = 0.95 # 温度衰减系数
k = 30 # 随机起点个数
x1, x2, y1, y2 = [], [], [], []
minx = []
n = 0
# 随机选取起始点,以求寻去全局最小值
initx1 = 20*(random.random()-0.5) # 确保有正有负,且要够分散
x1.append(initx1)
initx2 = 20*(random.random()-0.5)
x2.append(initx2)
# print("初始解x1:", initx1)
# print("初始解x2:", initx2)
nowT = initT
# 模拟退火算法寻找局部最小值过程
while nowT > minT:
for i in np.arange(1, iterL):
y = inputfun(initx1, initx2)
newx1 = initx1 + 20*(random.random()-0.5)
newx2 = initx2 + 20*(random.random()-0.5)
if newx1 >= -10 and newx1 <= 10:
if newx2 >= -10 and newx2 <= 10:
newy = inputfun(newx1, newx2)
dy = newy - y
if dy < 0:
initx1 = newx1