SisterRu

导航

 

1.首先编写M文件mengte.m定义目标函数f和约束向量g

%%%蒙特卡洛法
%%定义目标函数和约束向量函数
function [f, g] = mengte(x);
f = x(1) ^ 2 + x(2) ^ 2 + 3 * x(3) ^ 2 + 4 * x(4) ^ 2 + 2 * x(5) - 8 * x(1) - 2 * x(2) - 3 * x(3) - x(4) - 2 * x(5);
g = [sum(x) - 400
    x(1) + 2 * x(2) + 2 * x(3) + x(4) + 6 * x(5) - 800
    2 * x(1) + x(2) + 6 * x(3) - 200
    x(3) + x(4) + 5 * x(5) - 200];
end

2.编写M文件mainint.m,求问题的解

 1 %%%通过迭代求解
 2 rand('state', sum(clock)); %产生5个0-1之间的随机数
 3 p0 = 0;%p0代表目标值z,x0代表目标x
 4 tic
 5 for i = 1 : 10 ^ 6  %采集10^6个点
 6     x = 99 * rand(5, 1);%0<= x <= 99
 7 x1 = floor(x); x2 = ceil(x);%x1是x向下取整,x2是x向上取整
 8 [f, g] = mengte(x1);%对x1求值
 9 if sum(g <= 0) == 4%若满足4个则符合条件
10     if p0 <= f
11         x0 = x1;
12         p0 = f;
13     end
14 end
15 [f, g] = mengte(x2);%对x2求值
16 if sum(g <= 0) == 4
17     if p0 <= f
18         x0 = x2;
19         p0 = f;
20     end
21 end
22 end
23 x0, p0
24 toc

 

posted on 2019-07-20 23:19  yiruzhao  阅读(5961)  评论(0编辑  收藏  举报