I'm learning the basics of quantum mechanics from Binney and Skinner's book, and I'm trying to do a very basic exercise (2.5d), yet am struggling. The exercise is to calculate $\langle p^2 \rangle$. Super straightforward stuff. Here's why I'm a bit confused: if you apply the definition of the expectation value, you get that
\begin{align*} \langle p^2 \rangle = \langle \psi | p^2 | \psi \rangle. \end{align*}
Going a bit further, I wrote down the following calculations.
\begin{align*} \langle \psi | \hat{p} \circ \hat{p} | \psi \rangle & = \langle \psi | \hat{p} \left( \int dx \ |x \rangle \langle x | \hat{p} | \psi \rangle \right)\\\\ & = \langle \psi | \hat{p} \left( \int dx \ |x \rangle \left( -i \hbar \frac{\partial \psi}{\partial x} \right) \right)\\\\ & = - i \hbar \langle \psi | \hat{p} \left( \int dx \ |x \rangle \frac{\partial \psi}{\partial x} \right)\\\\ & = - i \hbar \left( \int dx \ \langle \psi | \hat{p} | x \rangle \frac{\partial \psi}{\partial x} \right)\\\\ & = - i \hbar \left( \int dx \ (\langle x | \hat{p} | \psi \rangle)^* \frac{\partial \psi}{\partial x} \right)\\\\ & = \hbar^2 \int dx \ \left( \frac{\partial \psi}{\partial x} \right)^* \frac{\partial \psi}{\partial x}. \end{align*} If you integrate by parts on the final answer, you can recover the "usual" answer of \begin{align*} \langle p^2 \rangle = - \hbar^2 \int dx \ \psi^* \frac{\partial^2 \psi}{\partial x^2}. \end{align*} My question is this: why do these two methods yield "different" initial answers? Is there anything deeper to this, or is it just a mathematical necessity?