Solution (source code)

= Solution

For the <harmonic-oscillator number-state second moments>, the <number operator> gives $\langle a^\dagger a\rangle_n=n$, while the <canonical commutation relation> gives $\langle aa^\dagger\rangle_n=n+1$. Terms with $a^2$ or $(a^\dagger)^2$ have zero diagonal <matrix elements>, since they change the <occupation number> by two. Therefore
$$
\begin{aligned}
\langle x^2\rangle_n
&=\frac{\hbar}{2m\omega}\langle a^2+(a^\dagger)^2+aa^\dagger+a^\dagger a\rangle_n
=\frac{\hbar(2n+1)}{2m\omega},\\
\langle p^2\rangle_n
&=-\frac{m\hbar\omega}{2}\langle (a^\dagger)^2+a^2-a^\dagger a-aa^\dagger\rangle_n
=\frac{m\hbar\omega(2n+1)}2.
\end{aligned}
$$
Consequently the <potential energy> and <kinetic energy> means are
$$
\boxed{\langle V\rangle_n=\frac12m\omega^2\langle x^2\rangle_n
=\frac12\hbar\omega\left(n+\frac12\right),\qquad
\langle T\rangle_n=\frac{\langle p^2\rangle_n}{2m}
=\frac12\hbar\omega\left(n+\frac12\right).}
$$
Their sum is the oscillator <energy eigenvalue> $E_n=\hbar\omega(n+1/2)$. Their equality is also the <virial theorem> result for a quadratic potential, here derived directly from the ladder operators.