# Inverting matrix then decomposing gives different quaternion than decomposing then inverting the quat

I'm getting different signs when I convert a matrix to quaternion and invert that, versus when I invert a matrix and then get the quaternion from it:

Quaternion a = Quaternion.Invert(getRotation(m));
Quaternion b = getRotation(Matrix.Invert(m));


I would expect a and b to be identical (or inverses of each other). However, it looks like q1 = (x, y, -z, -w) while q2 = (-x, -y, w, z). In other words, the Z and W components have been switched for some reason.

Note: getRotation() decomposes the transform matrix and returns just the rotation part of it (I've tried normalizing the result; it does nothing). The matrix m is a complete transform matrix and contains a translation (and possibly a scale) as well as a rotation. I'm using D3DXMatrixDecompose to do the actual decomposition.

Rotating a point p using a quaternion q is done with q * [0, p] / q. Replacing q with -q has absolutely no effect on the result.

If your rotations "go the wrong direction" when the sign of the quaternion changes, then the problem lies in the way you use the quaternions to rotate points.

• Eventually I turn them back into matrices using D3DXMatrixRotationQuaternion. Jul 27, 2012 at 15:53
• @Fraser can you maybe post an example of a rotation going wrong? Jul 27, 2012 at 20:57

Expressing rotations with quaternions can be done from an axis-angle representation, but not in a single way. For that same axis angle (w, a) pair, you get two quaternions performing the same task. One has its components based directly on the w vector and the a angle, the other has the same components, but negated. This is normal, since they describe the same rotation while the axis is pointing 180 degrees the other way and the angle is, this time, negated.

My hunch is that exactly this 1-to-1 failed mapping is what messes up things (i.e. the signs!!, not your weird rotations). It should not yield different rotation operations! Your getRotation function is the origin of those problems, but, I repeat, if q1 is approximately equal to -q2, then everything should be ok.

• getRotation is just a wrapper around D3DXMatrixDecompose Jul 27, 2012 at 15:50
• Yes, I saw the MSDN signature of this function. It also calls D3DXQuaternionRotationMatrix, which takes the pure rotation matrix to find an equivalent quaternion. That's no guarantee it will pick the q over the -q result.. how could it?? It's not aware of how you wish to have your rotation axes look like. It has two options and, due to numeric reasons, it chooses one over the other. Like Sam Hocevar also pointed out, it is not this result that's responsible for any of those problems. How are you using the quats to rotate 3D vectors? Could you drop a snippet? Jul 27, 2012 at 15:57

The problem turned out to be one of numerical stability. I was able to solve the problem by ortho-normalizing the input rotation matrix before doing the operation.