蚁群算法求最值c语言实现,蚁群算法代码(求函数最值).doc

蚁群算法代码(求函数最值).doc

function [F]=F(x1,x2) %目标函数

F=-(x1.^2+2*x2.^2-0.3*cos(3*pi*x1)-0.4*cos(4*pi*x2)+0.7);

End

function [maxx,maxy,maxvalue]=antcolony

% 蚁群算法求函数最大值的程序

ant=200; % 蚂蚁数量

times=50; % 蚂蚁移动次数

rou=0.8; % 信息素挥发系数

p0=0.2; % 转移概率常数

lower_1=-1; % 设置搜索范围

upper_1=1; %

lower_2=-1; %

upper_2=1; %

for i=1 : ant

X(i,1)=(lower_1+(upper_1-lower_1)*rand);

%随机设置蚂蚁的初值位置

X(i,2)=(lower_2+(upper_2-lower_2)*rand);

tau(i)=F(X(i,1),X(i,2)); %第i只蚂蚁的信息量

end %随机初始每只蚂蚁的位置

step=0.05; %网格划分单位

f='-(x.^2+2*y.^2-0.3*cos(3*pi*x)-0.4*cos(4*pi*y)+0.7)';

[x,y]=meshgrid(lower_1:step:upper_1,lower_2:step:upper_2);

z=eval(f); %eval函数,将字符串内的内容执行再赋给对象

figure(1);

mesh(x,y,z); %网格图

hold on;

plot3(X(:,1),X(:,2),tau,'k*') %蚂蚁初始位置

hold on;

text(0.1,0.8,-0.1,'蚂蚁的初始分部位置')

xlabel('x');ylabel('y');zlabel('f(x,y)');

for t=1:times % 第t次移动

lamda=1/t; %步长系数,随移动次数增大而减少

[tau_best(t),bestindex]=max(tau); %第t次移动的最优值及其位置

for i=1:ant %第i只蚂蚁

p(t,i)=(tau(bestindex)-tau(i))/tau(bestindex); %最优值与第i只蚂蚁的值的差比

% 计算状态转移概率

end

for i=1:ant

if p(t,i)

temp1=X(i,1)+(2*rand-1)*lamda; %移动距离

temp2=X(i,2)+(2*rand-1)*lamda;

else %全局搜索

temp1=X(i,1)+(upper_1-lower_1)*(rand-0.5);

temp2=X(i,2)+(upper_2-lower_2)*(rand-0.5);

end

%%%%%%%%%%%%%%%%%%%%%% 越界处理

if temp1

temp1=lower_1;

end

if temp1>upper_1

temp1=upper_1;

end

if temp2

temp2=lower_2;

end

if temp2>upper_2

temp2=upper_2;

end

%%%%%%%%%%%%%%%%%%%%%%%

if F(temp1,temp2)>F(X(i,1),X(i,2))

% 判断蚂蚁是否移动

X(i,1)=temp1;

X(i,2)=temp2;

end

end

for i=1:ant

tau(i)=(1-rou)*tau(i)+F(X(i,1),X(i,2)); % 更新信息量

end

end

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值