模擬退火

clear
clcdom

%生成初始解
sol_new2=1;%(1)解空間(初始解)
sol_new1=2-sol_new2^2;
sol_current1 = sol_new1; 
sol_best1 = sol_new1;
sol_current2 = sol_new2; 
sol_best2 = sol_new2;
E_current = inf;
E_best = inf;函數

rand('state',sum(clock)); %初始化隨機數發生器
t=90; %初始溫度
tf=89.9; %結束溫度
a = 0.99; %溫度降低比例ci

while t>=tf%(7)結束條件
    for r=1:1000 %退火次數
        
        %產生隨機擾動(3)新解的產生
        sol_new2=sol_new2+rand*0.2;
        sol_new1=2-sol_new2^2;
        
        %檢查是否知足約束
        if sol_new1^2-sol_new2>=0 && -sol_new1-sol_new2^2+2==0 && sol_new1>=0 &&sol_new2>=0
        else
            sol_new2=rand*2;
            sol_new1=2-sol_new2^2;
            continue;
        end
        
        %退火過程
        E_new=sol_new1^2+sol_new2^2+8;%(2)目標函數
        if E_new<E_current%(5)接受準則
                E_current=E_new;
                sol_current1=sol_new1;
                sol_current2=sol_new2;
                if E_new<E_best
                    %把冷卻過程當中最好的解保存下來
                    E_best=E_new;
                    sol_best1=sol_new1;
                    sol_best2=sol_new2;
                end
        else
                if rand<exp(-(E_new-E_current)/t)%(4)代價函數差
                    E_current=E_new;
                    sol_current1=sol_new1;
                    sol_current2=sol_new2;
                else
                    sol_new1=sol_current1;
                    sol_new2=sol_current2;
                end
        end
        plot(r,E_best,'*')
        hold on
    end
    t=t*a;%(6)降溫
endit

disp('最優解爲:')
disp(sol_best1)
disp(sol_best2)
disp('目標表達式的最小值等於:')
disp(E_best)io

 

---------------------------------function

function len=computer_tour(city,n) %計算路線總長度,每一個城市只計算和下家城市之間的距離。
len=0;
for i=1:n-1
len=len+sqrt((city(i).x-city(i+1).x)^2+(city(i).y-city(i+1).y)^2);
end
len=len+sqrt((city(n).x-city(1).x)^2+(city(n).y-city(1).y)^2);
end隨機數

------------------------------------di

function city=perturb_tour(city,n)

%隨機置換兩個不一樣的城市的座標
%產生隨機擾動
p1=floor(1+n*rand());
p2=floor(1+n*rand());while

while p1==p2
p1=floor(1+n*rand());
p2=floor(1+n*rand());
end
%exchange the random two cities
tmp=city(p1);
city(p1)=city(p2);
city(p2)=tmp;co

end

------------------------

function netplot(city,n) %連線各城市,將路線畫出來
hold on;
for i=1:n-1
plot(city(i).x,city(i).y,'r*');
line([city(i).x city(i+1).x],[city(i).y city(i+1).y]); %只連線當前城市和下家城市
end

plot(city(n).x,city(n).y,'r*'); line([city(n).x city(1).x],[city(n).y city(1).y]); %最後一家城市連線第一家城市 hold off;end

相關文章
相關標籤/搜索