利用遗传算法求函数f

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

长春师范大学实验报告

课程数学建模

系别15级数学与应用数学

班级数本四班

学号1507140432

姓名蒋佳诺

利用遗传算法求函数f(x)=10+x.*cos(5*pi*x),x∈[-1,1]的最大值点。代码如下:

clear all ;

clc ;

%%%%%清除所有之前的程序%%%%%

x=linspace(-1,1);

y=10+x.*cos(5*pi*x);

figure(1);

plot(x,y,’r’)

title(‘函数曲线图“)

xlabel(‘x’)

ylabel(‘y’)

%%%%%绘制图中函数图形%%%%%

%%主程序%%

global BitLength

%全局变量,计算如果满足求解精度至少需要编码的长度% global boundsbegin

%全局变量,自变量的起始点%

globalboundsend

%全局变量,自变量的终止点%

bounds=[-1,1]; %一维自变量的取值范围%

precision=0.0001;

%运算精度%

boundsbegin=bounds(:,1);

boundsend=bounds(:,2);

%计算如果满足求解精度至少需要多长的染色体% BitLength=ceil(log2((boundsend-boundsbegin)’./precision)); popsize=50;

%初始种群大小

Generationnmax=20;

%最大代数

pcrossover=0.90;

%交配概率

pmutation=0.09;

%变异概率

population=round(rand(popsize,BitLength));

%初始种群,行代表一个个体,列代表不同个体的%计算适应度

[Fitvalue,cumsump]=fitnessfun(population);

%输入群体population,返回适应度Fitvalue和累积概率cumsump

Generation=1;

While Generation

for j=1:2:popsize

%1对1对群体进行如下操作(交叉,变异)

%选择

seln=selection(population,cumsump);

%交叉

scro=crossover(population,seln,pcrossover);

scnew(j,:) =scro(1,:);

scnew(j+1,:) =scro(2,:);

%变异

smnew(j,:)=mutation(smnew(j,:),pmutation);

smnew(j+1,:)=mutation(smnew(j+1,:),pmutation);

end

%产生了新的种群

population=smnew;

%计算新种群的适应度

[Fitvalue,cumsump]=fitnessfun(population);

%记录当前代最好的适应度和平均适应度

[fmax,nmax]=max(Fitvalue);

%最好的适应度为fmax(即函数值最大),其对应的个体为nmax

fmean=mean(Fitvalue);

%平均适应度为fmean

ymax(Generation)=fmax;

%每代中最好的适应度

ymean(Generation)=fmax;

%每代中平均的适应度

%记录当前代的最佳染色体个体

x=transform2to10(population(nmax,:));

%population(nmax,:)为最佳染色体个体

xx=boundsbegin+x*(boundsend-boundsbegin)/(power(2,BitLength) -1);

xmax(Generation)=xx;

Generation=Generation+1

end

Generation=Generation-1;

%Generation 加1,减1的操作是为了能记录各代中的最佳函数值xmax(Generation)

targetfunvalue=targetfun(xmax)

[Besttargetfunvalue,nmax]=max(targetfunvalue)

Bestpopulation=xmax(nmax)

% 绘制经过遗传运算后的适应度曲线

figure(2);

hand1=plot(1:Generation,ymax);

set(hand1,’linestyle’,’-‘,’linewidth’,1,’marker’,’h’,markersize’,8)

hold on;

hand2=plot(1:Generation,ymean);

set(hand2,’color’,’k‘,’linestyle’,’-‘,’linewidth’,1,’marker’,’h’,markersiz e’,8)

xlabel(‘进化代数’)

ylabel(‘最大和平均适应度’);

xlim([1 Generationnmax]);

legend(‘最大适应度’,’平均适应度’);

box off;

hold off;

%%%%%%计算适应度函数%%%%%%

[Fitvalue,cumsump]=fitnessfun(population);

globalBitLength

globalboundsbegin

globalboundsend

popsize=size(population,1);

%计算个体个数

fori=1:popsize

x=transform2to10(population(i,:));

%将二进制转换为十进制

%转化为[-2,2]区间的实数

xx=boundsbegin+x*(boundsend-boundsbegin)/(power(2,BitLength)

相关文档
最新文档