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

1 view (last 30 days)
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 Comments
Birdman
Birdman on 27 Oct 2017
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 on 27 Oct 2017
It gives roughly the same answer. I've already tried that.

Sign in to comment.

Accepted Answer

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

More Answers (0)

Categories

Find more on Graphics Performance in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!