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

조회 수: 2 (최근 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);

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Graphics Performance에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by