資源簡介
使用matlab編程利用遺傳算法Max f (x1, x2) = 21.5 + x1·sin(4πx1) + x2·sin(20πx2)
s. t. -3.0 ≤ x1 ≤ 12.1
4.1 ≤ x2 ≤ 5.8
代碼片段和文件信息
%%%*****用遺傳算法求函數(shù)最大值(雙輸入單輸出)****%%%%%
clc;
clear;
x1min=-3.0;?%輸入變量1的變化范圍
x1max=12.1;???????
x2min=4.1;??%輸入變量2的變化范圍
x2max=5.8;??????????????????????????????????????
pb=0.001;??%變異概率
N=20;????%初始種群數(shù)目=20
s1=ceil(log2(1000*(x1max-x1min)));?%計(jì)算二進(jìn)制串的長度
s2=ceil(log2(1000*(x2max-x2min)));?
s=s1+s2;????%%種群的位數(shù)
zq=randi(Ns);?%產(chǎn)生初始種群,庫函數(shù)和for循環(huán)均可
%?for?i=1:N
%?????for?j=1:s
%?????????r=rand(1);
%?????????if?r>0.5
%?????????zq(ij)=1;
%?????????else?zq(ij)=0;
%?????????end
%?????end
%?end
%%*****用于二進(jìn)制轉(zhuǎn)化為十進(jìn)制****
for?i=1:s1
????zhuanhuan(i1)?=?2^(s1-i);
end
for?i=s1+1:s
????zhuanhuan(i1)?=?2^(s-i);
end
for?k=1:500?%遺傳算法的次數(shù)
????%%********將二進(jìn)制轉(zhuǎn)換成十進(jìn)制
????for??i=1:N
????????j1(i)=zq(i1:s1)*zhuanhuan(1:s1);
????????j2(i)=zq(is1+1:s)*zhuanhuan(s1+1:s);
????end?
????%%****轉(zhuǎn)化為目標(biāo)函數(shù)值
????x1=x1min+j1*(x1max-x1min)/(2^s1-1);
????x2=x2min+j2*(x2max-x2min)/(2^s2-1);
????%%****計(jì)算適配值?
????f=21.5+x1.*sin(4*pi*x1)+x2.*sin(20*pi*x2);
????%%%******依次得到最大值,平均值
????f_max(k)=max(f);
????f_sum=sum(f);
????f_avr(k)=sum(f)/N;
????%%******復(fù)制********?
????g=f/f_sum;??%計(jì)算選擇概率
??
評(píng)論
共有 條評(píng)論