Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

259
Views
Code for converting unit quaternions into spherical coordinates outputs the wrong result

I came across this stack overflow question titled Proper conversion between Quaternions and Spherical Rotation Coordinates? but trying the code out, the result did not equal my predictions. My question is, what did I do wrong?

I need to convert quaternions (x, y, z, w) into spherical coordinates (1, ฯ‘, ฯ†). I found a couple of solutions online, but none seem result in the correct values when I try it out in code. What I tried is converting the quaternions into an axis-angle representation, then trigonometrically calculating the ฯ‘ and ฯ† like demonstrated here. My python draft turns out to look like this:

def quaternion_to_spherical(qx, qy, qz, qw):

    angle_cos = qw
    angle_sin = math.sqrt(1 - math.pow(angle_cos, 2))
    angle = 2 * math.acos(qw)

    if angle_sin < 0.001:
        angle_sin = 1

    ax = qx / angle_sin
    ay = qy / angle_sin
    az = qz / angle_sin

    theta = -math.asin(ay)

    if math.pow(ax, 2) + math.pow(az, 2) < 0.001:
        phi = 0
    else:
        phi = math.atan2(ax, az)

    if phi < 0:
        phi = phi + math.pi * 2

    print("Theta: " + str(theta) + "\tPhi: " + str(phi))

However, the predefined results do not quite match. They should be as follows, with the output beneath:

Quaternion: [0.707, 0, 0, 0.707]
Result:     Theta: -0.0    Phi: 1.5707963267948966
Predicted:  Theta: ๐œ‹/2     Phi: 3๐œ‹/4

Quaternion: [0, 0.707, 0, 0.707]
Result:     Theta: -1.5707963118937354  Phi: 0
Predicted:  Theta: ๐œ‹/2                  Phi: 0

Quaternion: [0, 0, 0.707, 0.707]
Result:     Theta: -0.0    Phi: 0.0
Predicted:  Theta: 0       Phi: ๐œ‹/2 or 0

Any idea why these values are wrong? As far as I understand, there are no mistakes in the code. Is the math wrong, or are my predictions wrong?

If you care for the reason why I'm doing this, here it comes: I would like to apply 2x2 rotation matrices with complex numbers to 3D objects in Unity. The plan is to separate the math, which is taken from literature on bloch spheres from Unity's quaternion rotations. The conversion I'm doing here is the interface between Unity and the mathematical operations.

over 4 years ago ยท Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
ยฉ 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!