以下为求解表达式:
遗传算法构造过程:
程序流程图:
以下为算法程序:
%Generic Algorithm for function f(x1,x2) optimumclear all;close all;%ParametersSize=80; %群体的规模G=100; %终止迭代次数CodeL=10; %二进制编码长度 umax=2.048;umin=-2.048;%自变量取值范围E=round(rand(Size,2*CodeL)); %Initial Code/E为染色其种群,为80行20列的矩阵,矩阵的每一行为一个染色体%Main Programfor k=1:1:G %循环迭代的次数,循环迭代的条件time(k)=k; %时间轴,用于画图for s=1:1:Size %遍历整个解空间m=E(s,:); %取出其中一个染色体出来y1=0;y2=0; %染色体转换值初值%Uncodingm1=m(1:1:CodeL);for i=1:1:CodeL y1=y1+m1(i)*2^(i-1); %转化成十进制endx1=(umax-umin)*y1/1023+umin; %解码为X1的值,也就是解空间的值m2=m(CodeL+1:1:2*CodeL);for i=1:1:CodeL y2=y2+m2(i)*2^(i-1);endx2=(umax-umin)*y2/1023+umin; %解码为X1的值,也就是解空间的值F(s)=100*(x1^2-x2)^2+(1-x1)^2; %计算适应度endJi=1./F; %适应度的倒数,求最小值%****** Step 1 : Evaluate BestJ ******BestJ(k)=min(Ji); %保存最佳适应度的导数fi=F; %Fitness Function[Oderfi,Indexfi]=sort(fi); %Arranging fi small to bigger适应度从小到大排序Bestfi=Oderfi(Size); %Let Bestfi=max(fi) 取当前最大适应度BestS=E(Indexfi(Size),:); %Let BestS=E(m), m is the Indexfi belong to max(fi)最大适应度所对应的染色体bfi(k)=Bestfi; %保存当前最佳适应度%****** Step 2 : Select and Reproduct Operation****** fi_sum=sum(fi); %计算总体适应度 fi_Size=(Oderfi/fi_sum)*Size; %计算每个适应度下的染色体个数,相当于选择次数 fi_S=floor(fi_Size); %Selecting Bigger fi value,向下舍入 kk=1; for i=1:1:Size for j=1:1:fi_S(i) %Select and Reproduce TempE(kk,:)=E(Indexfi(i),:); kk=kk+1; %kk is used to reproduce end end %按照适应度大小从小到大排序 %************ Step 3 : Crossover Operation ************pc=0.60; %交叉概率n=ceil(20*rand); %选择随机交叉的切入点,rand产生[0,1]的随机数,ceil()正向取整for i=1:2:(Size-1) temp=rand; if pc>temp %Crossover Condition for j=n:1:20 TempE(i,j)=E(i+1,j); TempE(i+1,j)=E(i,j); end %相邻两个染色体,i控制染色体,j用于控制这个染色体上的那个点开始彼此交换 endendTempE(Size,:)=BestS; %保持最大适应度的编码稳定,防止数据震荡E=TempE; %************ Step 4: Mutation Operation突变操作 **************%pm=0.001;%pm=0.001-[1:1:Size]*(0.001)/Size; %Bigger fi, smaller Pm%pm=0.0; %No mutationpm=0.1; %Big mutation %变异概率 for i=1:1:Size %用于控制遍历所有染色体 for j=1:1:2*CodeL %用于遍历所有染色体上的位 temp=rand; if pm>temp %Mutation Condition if TempE(i,j)==0 TempE(i,j)=1; else TempE(i,j)=0; end end end end %Guarantee TempPop(30,:) is the code belong to the best individual(max(fi))TempE(Size,:)=BestS; %保持最大适应度的编码稳定,防止数据震荡E=TempE;end %迭代次数结束 Max_Value=Bestfi %输出函数的最大值BestS %最大适应度染色体编码x1 %X1取值x2 %X2取值figure(1);plot(time,BestJ); xlabel('Times');ylabel('Best J');figure(2);plot(time,bfi);xlabel('times');ylabel('Best F');