Is there a (fast) way to get a quaternion equivalent to another, but limited to +/- 180 degree rotation?

So I have a quaternion representing the difference between two other rotations:

Quaternion differenceRot = targetQuat * Quaternion.Inverse(sourceQuat);

Sometimes, depending on where source and target quaternions, are, the differenceRot will represent a very large rotation in the opposition direction of the shorter rotation. It’s the equivalent of rotating 340 degrees in one direction instead of 20 degrees in the other.

I can fix it by converting to angle and axis, then doing a “angle = (180 + angle) % 360 - 180;” thing, then converting the angle and axis back into a new Quaternion.

I assume this is slow.

Is there a faster way to do this? I don’t know anything about the internal coordinates of quaternions - is there anything analogous/similar to the “angle = (180 + angle) % 360 - 180” operation that I could do on the individual quaternion coordinates, or do I have to do do this conversion to and from angle/axis?

I believe this post is what you’re looking for:

In case the link becomes broken, here is the fix proposed over there:

public static Quaternion ShortestRotation(Quaternion a, Quaternion b)  
            if (Quaternion.Dot(a, b) < 0)
                return a * Quaternion.Inverse(Multiply(b, -1));
            else return a * Quaternion.Inverse(b);

 public static Quaternion Multiply(Quaternion input, float scalar)
            return new Quaternion(input.x * scalar, input.y * scalar, input.z * scalar, input.w * scalar);

Hope this helps!