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

2 次查看(过去 30 天)
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)?

请先登录,再进行评论。

采纳的回答

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