Something weird about vmath.quat_rotation_z

Newbie here. But having a weird problem. So, I have a code:

rotation = vmath.quat_rotation_z(math.rad(final_rotation))
pprint(rotation)
print(string.format("z: %.2f, w: %.2f, alpha: %.2f, alpha2: %.2f", rotation.z, rotation.w, math.acos(rotation.w)*2, math.asin(rotation.z)*2))

I assume that quat_rotation_z rotates around the Z identity vector (i.e. [0,0,1]), so z should be 1*sin(alpha/2) and w should be cos(alpha/2). And in 99 out of 100 cases that really is so: acos and asin return the same angle (up to a sign, but nevermind that).
Like:

DEBUG:SCRIPT: vmath.quat(0, 0, 0.16874966025352, 0.98565894365311)
DEBUG:SCRIPT: z: 0.17, w: 0.99, alpha: 0.34, alpha2: 0.34
DEBUG:SCRIPT: vmath.quat(0, 0, -0.26361832022667, 0.96462708711624)
DEBUG:SCRIPT: z: -0.26, w: 0.96, alpha: 0.53, alpha2: -0.53

But rarely, I get a different result:

DEBUG:SCRIPT: vmath.quat(0, 0, -0.97629600763321, -0.21643961966038)
DEBUG:SCRIPT: z: -0.98, w: -0.22, alpha: 3.58, alpha2: -2.71
DEBUG:SCRIPT: vmath.quat(0, 0, 0.99476635456085, -0.10217594355345)
DEBUG:SCRIPT: z: 0.99, w: -0.10, alpha: 3.35, alpha2: 2.94

Checking myself to make sure that quaternion is in fact normalized:
len = (( -0.97629600763321)^2+(-0.21643961966038)^2)^1/2 == 1

So it seems that I shouldn’t just do asin/acos for some reason, but I don’t really understand why =(

ps: euler.z sometimes returns something clearly wrong(different from what I get by manually converting quats), but searching through forum shows that it might be a known bug.

It’s still the same orientation, but measured as rotations in different directions. If you rotate something 3.58 rad it will end up at the same orientation as when you rotate it 2.71 rad in the opposite direction. The reason the sign is tricking you in the second case is because cos(0.1) == cos(-0.1). It might help to look at the unit circle and how to deal with the different quadrants. You can also have a look at math.atan which is common to use to get the angle since it has built in handling of the different cases.

3 Likes