How to multiply two quaternions by python or numpy [duplicate]
Asked Answered
A

1

6

I have two quaternions: Q1= w0, x0, y0, z0 and Q2 = w1, x1, y1, z1. I would like to multiply them by using NumPy or Python function which can return 2-d array. I found some pseudocodes on the internet which is written by Christoph Gohlke to do this kind of multiplication. I tried a lot but failed to apply it. Can anyone help me please to do this kind of multiplication? The pseudocodes are here: `

def quaternion_multiply(quaternion1, quaternion0):
w0, x0, y0, z0 = quaternion0
w1, x1, y1, z1 = quaternion1
return array([-x1*x0 - y1*y0 - z1*z0 + w1*w0,
                     x1*w0 + y1*z0 - z1*y0 + w1*x0,
                    -x1*z0 + y1*w0 + z1*x0 + w1*y0,
                     x1*y0 - y1*x0 + z1*w0 + w1*z0], dtype=float64)` 
Awn answered 17/8, 2016 at 15:30 Comment(4)
You just asked this yesterday: #38978941; comment or edit your question there if those answers aren't enough.Casto
@Casto I thought that people would not answer old question. It also happened to me no one answered my question rightly that I asked yesterday. Please do not mark it as duplicate question.Awn
My answer yesterday is basically the same as the one you accepted here. The only difference is that this one moves the np.array() step inside the function. If that's all that mattered you could have raised that issue in a comment.Casto
@Casto Sorry for misunderstanding. I am going to accept your answer now.Awn
P
9

Here's a little example using your function:

import numpy as np
import random


def quaternion_multiply(quaternion1, quaternion0):
    w0, x0, y0, z0 = quaternion0
    w1, x1, y1, z1 = quaternion1
    return np.array([-x1 * x0 - y1 * y0 - z1 * z0 + w1 * w0,
                     x1 * w0 + y1 * z0 - z1 * y0 + w1 * x0,
                     -x1 * z0 + y1 * w0 + z1 * x0 + w1 * y0,
                     x1 * y0 - y1 * x0 + z1 * w0 + w1 * z0], dtype=np.float64)

N = 4
for i in range(N):
    q1 = np.random.rand(4)
    q2 = np.random.rand(4)
    q = quaternion_multiply(q1, q2)
    print("{0} x {1} = {2}".format(q1, q2, q))
Ploughman answered 17/8, 2016 at 15:43 Comment(4)
I have already a python function which can create 2 arrays of quaternions. I am now trying to compute their product by using another function which should return the multiplication output.Awn
@Awn Ok, what part of my example is not clear then? I think I've already answered your question of I have two quaternions Q1 and Q2. I would like to multiply them by using NumPy or Python function which can return 2-d array , look at this line q = quaternion_multiply(q1, q2)Ploughman
Yes it works. Thanks :)Awn
Can you please help me to get output in arrays from the above function?Awn

© 2022 - 2024 — McMap. All rights reserved.