Potential Energy of a Magnetic Dipole
As $$\tau=MB\,\,sin\theta$$
If the dipole is rotated against the action of this torque, work has to be done. This work is stored as potential energy of the dipole
The work done in turning the dipole through a small angle $$d\theta$$ is
$$dW=\tau d\theta=MB\,\,sin\theta d\theta$$
If the dipole is rotated from an initial position $$\theta = \theta_{1}$$ to the final position $$\theta = \theta_{2}$$, then total work done will be
$$W=\int dW=\int_{\theta_{1}}^{\theta_{1}} MB sin \theta d\theta=-MB[-cos \theta]_{\theta_{1}}^{\theta_{2}}$$
=$$-MB(cos\theta_{2}-cos\theta_{1})$$
This work done is stored as the potential energy $$U$$ of the dipole.
$$\therefore U=-MB(cos\theta_{2}-cos\theta_{1})$$
The potential energy of the dipole is zero when
$$\overset{\rightarrow}{M}\,\,\bot\,\,\overset{\rightarrow}{B}$$So the potential energy of the dipole in any orientation $$\theta$$ can be obtained by putting $$\theta_{1}=90^{o}$$ and $$\theta_{2}$$
$$=\theta$$in the above eqaution.
$$\therefore=-MB(cos \theta-cos 90^{o})$$
or $$U=-MB cos\theta=M.B$$