Originally Posted by

**Roam** I want to write a matlab script that uses simulation to evaluate the following integral using 1000 iterations:

This is my code:

Code:

n=1000;
total=0;
for i=1:n
x= rand()*2+2;
y=x^2;
total=total+y;
end
expectation=total/n;
integral=expectation*4

The output is:

integral =

36.7483

But this answer is not even close!! Why is that? Can anyone show the problem with my code?

The eroor is:

Initialize x=2

and then for each ieration...x=x+.002

Hence, code will be

] Code:

n=1000;
total=0;
x=2;
for i=1:n
x= x+.002;
y=x^2;
total=total+y;
end
expectation=total/n;
integral=expectation*4