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

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 Kommentare

Birdman
Birdman am 27 Okt. 2017
Bearbeitet: Birdman am 27 Okt. 2017
a and b are the boundaries of x axis, c and d are the boundaries of y axis for corresponding values of a and b from x^2 function , right?
That is correct
Then why did you enter (0,10) for y boundaries where it has to be (1,4) for corresponding values of (1,2)?
It gives roughly the same answer. I've already tried that.

Melden Sie sich an, um zu kommentieren.

 Akzeptierte Antwort

If a is not zero, then “x_t = r_x*(b-a);” is wrong. It should be:
x_t = a + r_x*(b-a);

Weitere Antworten (0)

Community Treasure Hunt

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

Start Hunting!

Translated by