One must be aware of singularities in the Euler angle parametrization when the pitch approaches ±90° (north/south pole).
Code to handle the singularities is derived on this site: www.euclideanspace.com .