遗传算法应用案例

<>

案例一.无约束目标函数最大值遗传算法求解策略

求解问题           max f(x)=200*exp(-0.05*x)*\sin (x) ,x\in [-2,2]

%主程序:用遗传算法求解y=200*exp(-0.05*x).*sin(x)在[-2,2]上的最大值
clc;
clear all;
close all;
global BitLength
global boundsbegin
global boundsend
bounds=[-2 2];   %一维自变量的取值范围
precision=0.0001;%运算精度
boundsbegin=bounds(:,1);
boundsend=bounds(:,2);
%计算如果满足求解精度至少需要多长的染色体
BitLength=ceil(log2((boundsend-boundsbegin)'./precision));
popsize=50;       %初始种群大小
Generationnmax=30;%最大代数
pcrossover=0.90;  %交配概率
pmutation=0.09;   %变异概率
%产生初始种群
population=round(rand(popsize,BitLength));
%计算适应度,返回适应度Fitvalue和累计概率cumsump
[Fitvalue,cumsump]=fitnessfun(population);
Generation=1;
while Generation

 

function scro=crossover(population,seln,pc)
BitLength=size(population,2);
pcc=IfCroIfMut(pc);%根据交叉概率决定是否进行交叉操作,1则是,0则否
if pcc == 1
    chb=round(rand*(BitLength-2))+1;%在[1,BitLength-1]范围内随机产生一个交叉位
    scro(1,:)=[population(seln(1),1:chb) population(seln(2),chb+1:BitLength)];
    scro(2,:)=[population(seln(2),1:chb) population(seln(1),chb+1:BitLength)];
else
    scro(1,:)=population(seln(1),:);
    scro(2,:)=population(seln(2),:);
end
end
function [Fitvalue,cumsump]=fitnessfun(population)
global BitLength
global boundsbegin
global boundsend
popsize=size(population,1);
for i=1:popsize
   x=transform2to10(population(i,:));%将二进制转化为10进制
   %转化为[-2,2]区间的实数
   xx=boundsbegin+x*(boundsend-boundsbegin)/(power((boundsend),BitLength)-1);
   Fitvalue(i)=targetfun(xx);       %计算函数值,即适应度
end
%给适应度加上一个大小合理的数以便保证种群适应值为正数
Fitvalue=Fitvalue'+230;
%计算选择概率
fsum=sum(Fitvalue);
Pperpopulation=Fitvalue/fsum;
%计算累积概率
cumsump(1)=Pperpopulation(1);
for i=2:popsize
    cumsump(i)=cumsump(i-1)+Pperpopulation(i);
end
cumsump=cumsump';
end

 

function pcc=IfCroIfMut(mutORcro)
test(1:100)=0;
l=round(100*mutORcro);
test(1:l)=1;
n=round(rand*99)+1;
pcc=test(n);
end
function snnew=mutation(snew,pmutation)
    BitLength=size(snew,2);
    snnew=snew;
    pmm=IfCroIfMut(pmutation);%根据变异概率决定是否进行编译操作,1则是,0则不是
    if pmm == 1
       chb=round(rand*(BitLength-1))+1;%在[1,BitLength]范围内随机产生一个变异位
       snnew(chb)=abs(snew(chb)-1);
    end
end
function seln=selection(population,cumsump)
%从种群中选择两个个体
for i=1:2
    r=rand;         %随机产生一个随机数
    prand=cumsump-r;
    j=1;
    while prand(j)<0
        j=j+1;
    end
    seln(i)=j;      %选中个体的序号
end
end

 

function x=transform2to10(Population)
    BitLength=size(Population,2);
    x=Population(BitLength);
    for i=1:BitLength-1
        x=x+Population(BitLength-i)*power(2,i);
    end
end

 

function y=targetfun(x)
y = 200*exp(-0.05*x).*sin(x);
end

 

你可能感兴趣的:(数学,建模)