17161514131211051015202530图2.函数最大值随迭代次数变化曲线
可以看出,目标函数值随着迭代次数增加到8次即达到稳定状态,算法具有快速性和较强的全局寻优能力。 2.4下面对求解结果的准确性进行检查
在区间[0,10]上以0.01的步长进行搜索得到函数的最优值; 可得:x=0.32时函数取得最大值为 ymax =16.965539275225591 随着x值的变化,对应的y值为:
2015X: 0.32Y: 16.961050-5-10-15-20012345678910
图3.目标函数随x值的变化曲线
显然,采用遗传算法得到的结果比定步长的结果更好,且运算次数更少,达到了大于0.01的目标。
2.5方法的推广
本方法通过映射关系使遗传算法可以解决函数在浮点数范围内的函数最值问题,扩展了遗传算法的应用范围。
此外,如果把一个个体的编码划分为几节,分别对应不同自变量的编码,其余操作基本不变,则可以把遗传算法推广到多变量目标函数在给定区间上的最值的求取,并在结果精度和求解时间上均有较大提高。
附1、原程序代码
%参数的初始化,种群规模、染色体长度,交叉和变异概率;种群迭代次数; popsize=10;
chromlength=10; pc=0.5;
pm=0.04; circle=30;
maxindividual=zeros(1,circle);
bestcode=zeros(circle,chromlength); %对问题进行编码
initpop=round(rand(popsize,chromlength)); pop=initpop; times=0;
while times %对问题解码,即将2进制转化为10进制; decimal=zeros(1,popsize); for ii=1:popsize for jj=1:chromlength decimal(ii)=decimal(ii)+pop(ii,jj)*2.^(chromlength-jj); end decimal(ii)=10*decimal(ii)/1023; end %计算个体的适应度值; for i=1:popsize individual(i)=10*sin(5*decimal(i))+7*cos(decimal(i).^2); if(individual(i)<0) individual(i)=0; end end [maxindividual(times+1),maxindex]=max(individual);%每次迭代,种群中适应度的最大值; bestcode(times+1,:)=pop(maxindex,:);%适应度最高个体对应的编码; totalindividual=sum(individual); %进行选择操作; %转轮盘方法进行选择操作 for i=1:popsize bdindividual(i)=sum(individual(1:i))/totalindividual; end for i=1:popsize j=1; rn=rand; while rn>bdindividual(j) j=j+1; end newpop(i,:)=pop(j,:); end %个体间进行交叉操作,pcps(交叉位置); pop=newpop; for i=1:2:popsize rn2=rand; if(rn2 pcps=round(chromlength*rn2); if(pcps==0) pcps=1; end newpop(i,pcps:chromlength)=pop(i+1,pcps:chromlength); newpop(i+1,pcps:chromlength)=pop(i,pcps:chromlength); end end %对种群进行变异操作; for i=1:popsize for j=1:chromlength if(rand newpop(i,j)=1-newpop(i,j); end end end pop=newpop; times=times+1; end [maxall,index]=max(maxindividual); allindex=bestcode(index,:); value=0; for jj=1:chromlength value=value+allindex(jj)*2.^(chromlength-jj); end value=10*value/1023; fprintf('最佳编码序列为:');disp(allindex);disp('\\n'); fprintf('对应x的取值为:%8.5f\\n',value); fprintf('第 %d 次迭代达到最大值\\n',index); fprintf('求得最大值为 %f \\n',maxall); timeserie=zeros(1,times); for i=1:times timeserie(i)=max(maxindividual(1,1:i)); end figure; plot(1:times,timeserie); figure; sn = @(x) 10*sin(5*x)+7*cos(x.^2); fplot(sn,[0,10]) % xx=0:0.01:10; % yy=10*sin(5*xx)+7*cos(xx.^2); % [ymax,xmax]=max(yy)