How could I find the integral of a function given this code?

1 回表示 (過去 30 日間)
Gaëtan Poirier
Gaëtan Poirier 2017 年 10 月 27 日
コメント済み: Gaëtan Poirier 2017 年 10 月 27 日
I'm having trouble with a simple Monte Carlo integration code. It is as follows:
%define variables
Fun = @(x) x^2;
a = 1; % bounds for integration
b = 2;
c = 0;
d = 10;
n_under = 0; %total number of points that fall below the function
Int = 0; %integral is initially at 0
n_iter = 1000000; %total number of points
for i =1:n_iter
%random number generator
r_x = rand();
x_t = r_x*(b-a); %for x values
r_y = rand();
y_t = r_y*(d-c); %for y values
if Fun(x_t) > y_t
n_under = n_under + 1; %Monte Carlo "walk", if the points fall below the function, then we add, else we
end %don't add
end
Int = n_under/n_iter * (b - a) * (d - c) %final function
hold on;
x = 0:.1:10;
y = Fun(x);
plot (a,c,'o',b,d,'o',a,d,'o',b,c,'o')
plot (x,y) %just plotted the function here to make sure the plot is good. it is
I'm having trouble when I change the bounds of integration. Specifically if I use bounds (0,1) for almost any function, it works perfectly (with some error, of course), however if, such as above is use bounds (1,2) or other (anything that is not a = 0) the code outputs the wrong answer. Could anyone help with this issue? Much thanks!
  4 件のコメント
Birdman
Birdman 2017 年 10 月 27 日
Then why did you enter (0,10) for y boundaries where it has to be (1,4) for corresponding values of (1,2)?
Gaëtan Poirier
Gaëtan Poirier 2017 年 10 月 27 日
It gives roughly the same answer. I've already tried that.

サインインしてコメントする。

採用された回答

Roger Stafford
Roger Stafford 2017 年 10 月 27 日
If a is not zero, then “x_t = r_x*(b-a);” is wrong. It should be:
x_t = a + r_x*(b-a);
  1 件のコメント
Gaëtan Poirier
Gaëtan Poirier 2017 年 10 月 27 日
That's exactly it. Thank you so much!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeGraphics Performance についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by