# Q：正态分布实现[复制]

Hi I am trying to generate values using Matlab for the question below:

Let x be a random variable with distribution N(0,1). Determine in an exact or approximate way:

E{x^2}

``````X=[-5:5];
Y=normpdf(X);
x2=X.*X;
ex2=sum(x2.*Y);
``````

I get the answer 1 which I assume is correct. But when I increase the realizations of X, i.e.

``````X=[-5:0.5:5];
Y=normpdf(X);
x2=X.*X;
ex2=sum(x2.*Y);
``````

I get the answer as 2. Am I going wrong somewhere?

e { x 2 }

``````X=[-5:5];
Y=normpdf(X);
x2=X.*X;
ex2=sum(x2.*Y);
``````

``````X=[-5:0.5:5];
Y=normpdf(X);
x2=X.*X;
ex2=sum(x2.*Y);
``````

You are numerically computing the second moment of a Gaussian random variable. That's expressed in terms of the pdf as an integral, which you approximate by a sum.

To approximate the integral by a sum, you need to multiply by the sampling step used on the x axis. (you can think that the "dx" in the integral is replaced by a non-infinitesimal "Δx"). The step is 1 in the first case, and 0.5 in the second.

So you need to multiply your second result by the step 0.5.

matlab  probability  normal-distribution