程式語言我選擇的是MATLAB,代碼如下:
%% 開始clcclearclose all%% 參數準備a=0.95; %溫度衰減速度times=1000; %循環次數k=[34 32 56 67 54 32 45 56 46 70]; %物品價值d=[8 12 24 16 6 9 35 21 18 19]; %物品重量restriction=50; %背包能夠承受的最大重量t0=97;tf=3;t=t0; %溫度設置num=length(k); %物品數量
sol_new=round(rand(1,num)); %隨機生成初始解E_current=inf;E_best=inf; %E_current是當前解對應的目標函數,E_best是最優解,E_new是新解的目標函數值%% 模擬退火while t>tf
for i=1:times sol_new=chage(sol_new,num,d,restriction); end
%計算價值 E_new=sol_new*(-k'); if E_new<E_current E_current=E_new; sol_current=sol_new;
if E_new<E_best E_best=E_new; sol_best=sol_new; end
else
if Metropolis(E_new,E_current,t) E_current=E_new; sol_current=sol_new; else sol_new=sol_current; end
end
t=t*a; %溫度衰減
end%% 輸出disp('最優解為')sol_bestdisp('物品總價值為')-E_bestdisp('背包中物品總重量')sol_best*d'function [sol_new] = chage(sol_new,num,d,restriction)%對x進行隨機擾動並使其滿足約束條件 %產生隨機擾動 temp1=ceil(rand*num); sol_new(1,temp1)=~sol_new(1,temp1);
%檢查是否滿足約束 while (1) s=(sol_new*d'>restriction); if s %如果不滿足約束隨機放棄一個物品
temp2=find(sol_new==1); temp3=ceil(rand*length(temp2)); sol_new(temp2(temp3))=~sol_new(temp2(temp3)); else break end endendfunction [p] = Metropolis(E_new,E_current,t0)%Metropolis準則f=exp( ( E_new-E_current )./t0 );a=rand;if a>=f p=1;else p=0;end
初次嘗試,若有不足,望能指正