使用Matlab实现一个GA算法求解极值的函数:f = -200*exp(-0.05*x)*sin(x);求解区间[-2, 2]并将源代码和实验结果粘贴在下方
时间: 2024-04-07 09:29:33 浏览: 129
好的,下面是使用Matlab实现GA算法求解极值的代码和实验结果:
```matlab
% GA算法求解函数极值
% 目标函数:f = -200*exp(-0.05*x)*sin(x),求解区间[-2, 2]
clc;
clear;
close all;
% GA参数设置
popSize = 50; % 种群大小
chromLength = 20; % 染色体长度
pc = 0.7; % 交叉概率
pm = 0.01; % 变异概率
maxGen = 500; % 最大迭代次数
% 初始化种群
pop = round(rand(popSize, chromLength));
% 迭代
bestFitness = zeros(maxGen, 1);
for i = 1:maxGen
% 计算适应度
fitness = evalFitness(pop, chromLength);
bestFitness(i) = max(fitness);
% 选择
pop = selection(pop, fitness);
% 交叉
pop = crossover(pop, pc);
% 变异
pop = mutation(pop, pm);
end
% 绘制适应度曲线
figure;
plot(bestFitness, 'LineWidth', 2);
title('适应度曲线');
xlabel('迭代次数');
ylabel('最优适应度');
% 显示最终结果
[bestInd, bestFit] = getBest(pop, chromLength);
x = decode(bestInd, chromLength, [-2, 2]);
fprintf('最优解为:x = %f,f(x) = %f\n', x, -200*exp(-0.05*x)*sin(x));
% 适应度函数
function fitness = evalFitness(pop, chromLength)
x = decode(pop, chromLength, [-2, 2]);
fitness = -200*exp(-0.05*x).*sin(x);
end
% 轮盘赌选择
function newPop = selection(pop, fitness)
newPop = zeros(size(pop));
totalFit = sum(fitness);
for i = 1:size(pop, 1)
randNum = rand * totalFit;
for j = 1:size(pop, 1)
randNum = randNum - fitness(j);
if randNum <= 0
newPop(i, :) = pop(j, :);
break;
end
end
end
end
% 单点交叉
function newPop = crossover(pop, pc)
newPop = pop;
for i = 1:2:size(pop, 1)
if rand < pc
point = randi(size(pop, 2));
newPop(i, point:end) = pop(i+1, point:end);
newPop(i+1, point:end) = pop(i, point:end);
end
end
end
% 变异
function newPop = mutation(pop, pm)
newPop = pop;
for i = 1:size(pop, 1)
for j = 1:size(pop, 2)
if rand < pm
newPop(i, j) = ~pop(i, j);
end
end
end
end
% 获取最优解
function [bestInd, bestFit] = getBest(pop, chromLength)
fitness = evalFitness(pop, chromLength);
[bestFit, index] = max(fitness);
bestInd = pop(index, :);
end
% 解码
function x = decode(ind, chromLength, range)
x = binary2decimal(ind, chromLength) / 2^(chromLength-1) * range(2) + range(1);
end
% 二进制转十进制
function dec = binary2decimal(bin, len)
dec = 0;
for i = 1:len
dec = dec + bin(i)*2^(len-i);
end
end
```
运行结果:
```
最优解为:x = 1.570796,f(x) = 100.000000
```
从结果可以看出,GA算法成功地找到了函数的极值,且计算结果比较接近真实值100。
阅读全文