模拟退火算法实现寻找函数最值

模拟退火的算法思想

模拟退火算法从某一较高初温出发,伴随温度参数的不断下降,结合概率突跳特性在解空间中随机寻找目标函数的全局最优解,即在局部最优解能概率性地跳出并最终趋于全局最优。

模拟退火算法模板:

初始温度
T=100
冷却速率
rate=0.99
while T>1:
    随机生成一个解
    x=random
    随机解的适应度
    y=f(x)
    如果当前适应度大于最佳适应度,则保存新解
    if y>Y:
        X=x
        Y=y
    else:
*算法核心如果当前适应度小于最佳适应度,则以一定概率保存新解,这个概率由适应度差值和当前温度决定,差值越小,温度越大,概率越大
        if exp(-(Y-y)/T)>random():
            X = x
            Y = y
    冷却
    T*=rate

例子:

求解f(x)=x+5sin(5x)+2cos(4x)在区间上的函数最值。

代码

import numpy as np
import matplotlib.pyplot as plt
import math
import random

def aimFunction(x):
    y=x+5*math.sin(5*x)+2*math.cos(4*x)
    return y

start=0
end=10

X=random.uniform(start,end)
Y=aimFunction(X)

T=100
rate=0.99
while T>1:
    x=random.uniform(start,end)
    y=aimFunction(x)
    if y>Y:
        X=x
        Y=y
    else:
        if math.exp(-(Y-y)/T)>random.random():
            X = x
            Y = y
    T*=rate

print(X,Y)

猜你喜欢

转载自blog.csdn.net/springtostring/article/details/82222661