【问题标题】:Monte Carlo style to evaluate an integral MATLAB蒙特卡洛风格评估积分 MATLAB
【发布时间】:2017-11-10 21:44:49
【问题描述】:

我知道我们可以使用蒙特卡洛方法来近似 pi,方法是在右上角“抛出”点并计算其中有多少在圆圈内等。

我想对 每个函数 f 都这样做,所以我在矩形 [a,b] x [0; 中“抛出”随机点 max(f)] 并且我正在测试我的 random_point_y 是否低于 f(random_point_x),然后我将总数除以 f 下方的点数。
这是代码:

clear
close all
%Let's define our function f
clear
close all
f = @(x) exp(-x.^2);
a=-1; b=1;
range = [a:0.01:b];
f_range = f(range);

%Let's find the maximum value of f
max_value = f(1);
max_x = range(1);
for i = range
    if (f(i) > max_value) %If we have a new maximum
        max_value = f(i);
        max_x = i;
    end
end


n=5000;
count=0;
%Let's generate uniformly distributed points over [a,b] x [0;max_f]
x = (b-a)*rand(1,n) + a;
y = rand(1,n) * max_value;

for i=1:n
    if y(i)<f(x(i)) %If my point is below the function
        count = count + 1;
    end
end


%PLOT
hold on

%scatter(x,y,'.')
plot(range,f_range,'LineWidth',2)
axis([a-1 b+1 -1 max_value+1])
integral = (n/count)

hold off

例如我有 f = e^(-x^2) 在 -1 和 1 之间:

但我的结果 1.3414,1.3373 获得 500.000 分。 确切的结果是 1.49365

我错过了什么?

【问题讨论】:

  • 顺便说一句,你可以这样做:a=-1;b=1;f = @(x) exp(-x.^2);n=5000;randnums=a+(b-a)*rand(1,n);intg=(b-a)*mean(f(randnums))
  • 是的,它可以工作,但我真的很想实现那个“射击”。而且,如果我将f = @(x) exp(-x.^2); 和测试设置为if x(i)^2+y(i)^2 &lt;= 1,它会得到同样的错误,所以我真的不知道它来自哪里..

标签: matlab montecarlo approximation


【解决方案1】:

你有两个小错误:

  • 应该是count/n,而不是n/count。使用正确的count/n 将给出曲线下方点的比例
  • 要获得曲线下方的面积,请将该比例乘以矩形的面积,(b-a)*max_value

所以,请使用count/n * (b-a)*max_value


除此之外,通过一些矢量化,您的代码会更快、更清晰:

clear
close all
f = @(x) exp(-x.^2);
a=-1; b=1;
range = [a:0.01:b];

%Let's find the maximum value of f
max_value = max(f(range));

n=50000;
%Let's generate uniformly distributed points over [a,b] x [0;max_f]
x = (b-a)*rand(1,n) + a;
y = rand(1,n) * max_value;

count = sum(y < f(x));
result = count/n * (b-a)*max_value

【讨论】:

  • @RomainB。好吧,它替换了循环中的count = count + 1y &lt; f(x) 与等大小向量的比较给出了一个向量,其条目等于 true (1) 或 false(0),而 sum 只计算总和
猜你喜欢
  • 2014-03-26
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
  • 2012-12-11
  • 2011-11-24
  • 2020-07-05
  • 2021-04-20
  • 1970-01-01
相关资源
最近更新 更多