<s>[INST] When is $E(X-\mu)^2 \ne E(X^2)-\mu^2$? Consider the probability density function
$$f(x)=\frac{x}{18}, \quad x \in [0,18]$$
Find $E(x)$ and $Var(x)$.

Solution:
a.)
\begin{align*}
E(x)
&=\int_{-\infty}^{\infty} x f(x) dx \\
&=\int_{0}^{18} x \left(\frac{x}{18}\right) dx \\
&=\frac{1}{18} \int_0^{18} x^2 dx \\
&=108
\end{align*}
b.)
Method 1:
\begin{align*}
Var(x)
&=E(x-\mu)^2 \\
&=\int_{-\infty}^{\infty} (x-\mu) f(x) dx \\
&=\int_{0}^{18} (x-108)^2 \left(\frac{x}{18}\right) dx \\
&=83106
\end{align*}
Method 2:
\begin{align*}
Var(x)
&=E(x^2)-\mu^2 \\
&=\int_{-\infty}^{\infty} x^2 f(x) dx - (108)^2 \\
&=\int_{0}^{18} x^2 \left(\frac{x}{18}\right) dx - (108)^2\\
&=\frac{1}{18}\int_{0}^{18} x^3 dx - (108)^2\\
&=-10206
\end{align*}
Clearly the second method is wrong, since a variance cannot be negative. But I cannot find the error. Can someone explain why the two methods yield different values? Is it not always the case that  $E(X-\mu)^2 \ne E(X^2)-\mu^2$?
 [/INST] The probability density function integrates to 9 in the interval given, that is why it does not work.
</s>