Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

263
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda