You are on page 1of 3

Tìm giá trị lớn nhất của hàm số sau đây sử dụng thuật toán GA(Genetic Algorithms) dùng

phần
mềm matlab. Cho biết số thế hệ tối đa là 50, số cá thể là 10, hệ số lai ghép CR=0.5, hệ số đột
biến MR=0.05. Với -5<=x,y<=5.
4 3 2
f ( x)   
( x  2)  ( y  2)  1 ( x  2)  ( y  2)  1 ( x  2)  ( y  2) 2  1
2 2 2 2 2

function example_GA
% Genetic Algorithms
%--------------------------------------------------------------
% Reference book "A Tutorial on Meta-Heuristics for Optimization"
% Authors: Shu-Chuan Chu, Chin-Shiuh Shieh, and John F. Roddick
%--------------------------------------------------------------

% --Initialize Parameters---
n = 10; % Population Size
cl = 32; % Number of bits in each chromosome
c = zeros(n,cl);
mg = 50; % %Maximal Number of Generations
best_f = -10^9; % Best Fitness Value
f = zeros(1,n);
best_c = zeros(1,cl); % Best Chromosome
p = zeros(1,n);
tmpc=zeros(n,cl);
CR = 0.5; % Crossover Rate
MR = 0.05; % Mutation Rate
Fvl=zeros(1,cl);

% Initialize Population
for i=1:1:n
for j=1:1:cl
if(rand(1)<0.5)
c(i,j)=0;
else
c(i,j)=1;
end
end
end

% Main Program
for t=1:1:mg
%--Decode Chromosome--
x = zeros(1,n);
y = zeros(1,n);
for i=1:1:n
for j=1:1:cl/2
x(i) = x(i)*2+c(i,j);
end
x(i)=10*x(i)/(2^16)-5;
for j = (cl/2+1):1:cl
y(i) = y(i)*2+c(i,j);
end
y(i)=10*y(i)/(2^16)-5;
%--Update best solution--
f(i) = 4/((x(i)-2)^2+(y(i)-2)^2 +1)+3/((x(i)-2)^2+(y(i)+2)^2
+1)+2/((x(i)+2)^2+(y(i)-2)^2 +1);
if(f(i) > best_f)
best_f = f(i);
for j=1:1:cl
best_c(j)=c(i,j);
end
end
end

% Evaluate Selection Probability


tmpf =0;
for i = 1:1:n
p(i) = (f(i))^2;
tmpf = tmpf + p(i);
end
for i = 1:1:n
p(i) = p(i)/tmpf;
end
% Save the best solution
for j=1:1:cl
tmpc(1,j)=best_c(j);
end
%--Roulette wheel selection--
for i=2:1:n
tmpf = rand(1);
for k=1:1:n
tmpf = tmpf - p(k);
if tmpf<0
g=k;
break;
end
end
for j=1:1:cl
tmpc(i,j)=c(g,j);
end
end
%--Copy temporary population to population--
for i=1:1:n
for j=1:1:cl
c(i,j)=tmpc(i,j);
end
end
%--Crossover---
for i = 1:2:(n-1)
a = rand(1);
if(a<CR)
site = a*cl;
j=1;
while (j<site)
tmpi = c(i,j);
c(i,j) = c(i+1,j);
c(i+1,j)= tmpi;
j=j+1;
end
end
end
%--Mutation---
for i=1:1:n
for j =1:1:cl
if (rand(1)<MR)
c(i,j)=1-c(i,j);
end
end
end
%--Return F(x,y) have found out in each Generations---
r=0;
q=0;
for j=1:1:cl/2
r = r*2+best_c(j);
end
r=10*r/(2^16)-5;
for j = (cl/2+1):1:cl
q = q*2+best_c(j);
end
q=10*q/(2^16)-5;
Fvl(t) = 4/((r-2)^2+(q-2)^2 +1)+3/((r-2)^2+(q+2)^2 +1)+2/((r+2)^2+...
(q-2)^2 +1);

end
% ---Export Graph---
disp(Fvl);
plot(Fvl);
hold on;
end

You might also like