遗传算法计算 f(x) = 1-x^2的最大值
x 的区间是 -1<= x <= 1
F = @(x)1-x.^2;
f = @(x)2/(2^11-1)*x-1;
s = round(rand(8,11));
s = num2str(s);
s(find(s==' '))=[];
s = reshape(s, 8, 11);
for j = 1:10000
for i = 1:2
k = round(rand(1)*8)+1;
if k == 9
k = 8;
end
temp = s(k, :);
wei = round(rand(1)*11)+1;
if wei == 12
wei = 11;
end
if temp(wei) == '1'
temp(wei) = '0';
else
temp(wei) = '1';
end
s = [s ; temp];
end
for i = 3
k = round(rand(1, 2)*8)+1;
a = s(k(1), :);
b = s(k(2), :);
wei = round(rand(1, 2)*11)+1;
temp = a(wei : 11);
a (wei : 11) = b(wei : 11);
b(wei : 11) = temp;
s = [s ; a; b];
end
[ff bin] = sort(F(f(bin2dec(s))), 'descend');
s = [s(bin(1:8), :)];
end
F(f(bin2dec(s)))