# Thread: Estimating an integral using Matlab

1. ## Estimating an integral using Matlab

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

$\displaystyle \int^4_2 x^2 dx$

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?

2. Originally Posted by Roam
I want to write a matlab script that uses simulation to evaluate the following integral using 1000 iterations:

$\displaystyle \int^4_2 x^2 dx$

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:
Code:


x= rand()*2+2;
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

3. Originally Posted by Roam
I want to write a matlab script that uses simulation to evaluate the following integral using 1000 iterations:

$\displaystyle \int^4_2 x^2 dx$

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?
$\displaystyle E(X^2)$ when $\displaystyle X\sim U(2,4)$ is:

$\displaystyle \int_{x=2}^4 x^2 p(x)\;dx$

but $\displaystyle p(x)=1/2$ for $\displaystyle x \in [2,4]$, so:

$\displaystyle E(X^2)=\frac{1}{2}\int_{x=2}^4 x^2\;dx$

or:

$\displaystyle \int_{x=2}^4 x^2\;dx=2E(X^2)$

and you have use $\displaystyle 4$ instead of $\displaystyle 2$.

CB

4. Originally Posted by malaygoel
The eroor is:
Code:


x= rand()*2+2;
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
Numerical integration does not qualify as "simulation" in the context of this problem, and you still have the same error as the OP, which is the *4 in the last line.

The OP's Monte-Carlo code was as correct as yours (it has the same error).

CB