⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ga.m

📁 标准遗传算法求解实数方程
💻 M
字号:
%% generitic algrithm
%% floating encoding
%% f(x)=x1^2+x2^2
%% min f(x)
clear;
clc;
rand('state',sum(100*clock))
NP=30;
pm=0.05;
pc=0.8;
alaf=0.5;
dimentions=2;
b=0.5;
UB=30;
LB=-30;
Maxiterations=50;
child=rand(NP,dimentions)*(UB-LB)+LB;  %% initialize 
farther=child;
iterations=0;
bestfx=[];
while iterations<Maxiterations
%% computer the fitness
for p=1:NP
    x1=farther(p,1);
    x2=farther(p,2);
    fx(p)=x1^2+x2^2;
    fitness(p)=1/(fx(p)+0.0000001);    
end
[X,I]=sort(fitness);
bestnumber=I(NP);
bestfx(iterations+1)=min(fx);

%% computer the fitness accumulation
for p=1:NP
    if p==1
        fitacc(p)=fitness(p);
    else
        fitacc(p)=fitacc(p-1)+fitness(p);
    end
end
%% copy operation
for p=1:NP
    if p==bestnumber
        child(p,:)=farther(p,:);
    else
        randfit=rand*fitacc(NP);
    
        for i=1:NP
            if fitacc(i)>=randfit
                break;
            end            
        end
        child(p,:)=farther(i,:);
    end
end

%% crossover operation
for number1=1:NP
    if number1==bestnumber
        child(number1,:)=child(number1,:);
    else
        number2=number1;
        
        while number2==number1
            number2=rand*NP;
            number2=number2-rem(number2,1)+1;
        end
    
        if pc>rand
            child(number1,:)=alaf*child(number1,:)+(1-alaf)*child(number2,:);
        else
            child(number1,:)=child(number1,:);
        end
    end
end

%% mutate operation
for p=1:NP
    if p==bestnumber
        child(p,:)=child(p,:);
    else
        if pm>rand
            deta=rand;
            power=(1-iterations/Maxiterations)^b;
            d=rand*dimentions;
            d=d-rem(d,1)+1;
            if (rand-0.5)>0
                child(p,d)=child(p,d)+(UB-child(p,d))*(1-deta^power);                
            else
                child(p,d)=child(p,d)-(child(p,d)-LB)*(1-deta^power);
            end
        else
            child(p,:)=child(p,:);
        end
    end
end
farther=child;
iterations=iterations+1;
end
hold on
plot(bestfx);
for i=1:Maxiterations
    if bestfx(i)<0.001
        plot(i,bestfx(i),'r*');
        break;
    end
end

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -