Here's the fastest quaternion multiplication implementation in Python:
python
import numpy as np
from numba import njit
@njit
def quat_mult_numba(q1, q2):
"""
Multiply two quaternions using Numba JIT compilation.
Quaternions are in [w, x, y, z] format.
"""
w1, x1, y1, z1 = q1
w2, x2, y2, z2 = q2
return np.array([
w1*w2 - x1*x2 - y1*y2 - z1*z2,
w1*x2 + x1*w2 + y1*z2 - z1*y2,
w1*y2 - x1*z2 + y1*w2 + z1*x2,
w1*z2 + x1*y2 - y1*x2 + z1*w2
])
# Alternative: Pure NumPy vectorized for batch operations
def quat_mult_batch(q1, q2):
"""
Multiply quaternions in batch.
q1, q2 shape: (N, 4) where N is batch size
"""
w1, x1, y1, z1 = q1[..., 0], q1[..., 1], q1[..., 2], q1[..., 3]
w2, x2, y2, z2 = q2[..., 0], q2[..., 1], q2[..., 2], q2[..., 3]
w = w1*w2 - x1*x2 - y1*y2 - z1*z2
x = w1*x2 + x1*w2 + y1*z2 - z1*y2
y = w1*y2 - x1*z2 + y1*w2 + z1*x2
z = w1*z2 + x1*y2 - y1*x2 + z1*w2
return np.stack([w, x, y, z], axis=-1)
# For single quaternions without dependencies
def quat_mult_pure(q1, q2):
"""
Pure Python implementation - fastest for single operations
without NumPy overhead.
"""
w1, x1, y1, z1 = q1
w2, x2, y2, z2 = q2
return (
w1*w2 - x1*x2 - y1*y2 - z1*z2,
w1*x2 + x1*w2 + y1*z2 - z1*y2,
w1*y2 - x1*z2 + y1*w2 + z1*x2,
w1*z2 + x1*y2 - y1*x2 + z1*w2
)
Performance characteristics:
quat_mult_numba: Fastest for repeated single quaternion multiplications. The JIT compilation overhead is amortized over multiple calls.
quat_mult_batch: Fastest for multiplying many quaternion pairs simultaneously. NumPy's vectorization provides excellent performance for batch operations.
quat_mult_pure: Fastest for one-off single quaternion multiplications where you want to avoid NumPy/Numba overhead.
For maximum performance in a real application, consider:
Use quat_mult_numba if you're doing many individual multiplications in a loop
Use quat_mult_batch if you can structure your data to multiply many quaternions at once
Pre-allocate output arrays if doing many operations
Consider using np.float32 instead of np.float64 if precision requirements allow
The Numba version typically provides 10-50x speedup over pure Python for repeated operations, while the batch version can process thousands of quaternions with near-C performance.