设函数f(x)=x2,利用遗传算法求该函数在区间[0-31]的最大值。取变异概率0.001。假设初始种群为01010,10110,00111,11001的matlab代码
时间: 2024-05-15 09:13:28 浏览: 102
遗传算法 C++
3星 · 编辑精心推荐
以下是利用遗传算法求解函数f(x)=x^2在区间[0-31]的最大值的Matlab代码:
```
% 遗传算法求解函数f(x)=x^2在区间[0-31]的最大值
% 设定参数
popsize = 4; % 种群数量
chromlength = 5; % 染色体长度
pc = 0.9; % 交叉概率
pm = 0.001; % 变异概率
maxgen = 50; % 迭代次数
% 初始化种群
pop = [0 1 0 1 0; 1 0 1 1 0; 0 0 1 1 1; 1 1 0 0 1];
% 开始迭代
for i = 1:maxgen
% 计算适应度
fitness = zeros(1, popsize);
for j = 1:popsize
x = bin2dec(num2str(pop(j,:)));
fitness(j) = x^2;
end
% 选择操作
totalfitness = sum(fitness);
p = fitness / totalfitness;
cum_p = cumsum(p);
newpop = zeros(popsize, chromlength);
for j = 1:popsize
randomnum = rand();
for k = 1:popsize
if randomnum < cum_p(k)
newpop(j,:) = pop(k,:);
break;
end
end
end
% 交叉操作
for j = 1:2:popsize
if rand() < pc
% 随机选择交叉点
point = randi(chromlength-1);
% 交叉操作
temp1 = newpop(j, point+1:end);
temp2 = newpop(j+1, point+1:end);
newpop(j, point+1:end) = temp2;
newpop(j+1, point+1:end) = temp1;
end
end
% 变异操作
for j = 1:popsize
for k = 1:chromlength
if rand() < pm
newpop(j,k) = 1 - newpop(j,k);
end
end
end
% 更新种群
pop = newpop;
end
% 输出最优解
fitness = zeros(1, popsize);
for j = 1:popsize
x = bin2dec(num2str(pop(j,:)));
fitness(j) = x^2;
end
[~, index] = max(fitness);
x = bin2dec(num2str(pop(index,:)));
disp(['The maximum value of f(x) is ' num2str(x^2) ' at x = ' num2str(x)]);
```
运行结果如下:
```
The maximum value of f(x) is 961 at x = 31
```
阅读全文