# How To Multiply Two Quaternions Together Using Python

Here is how we multiply two quaternions together using Python. Multiplying two quaternions together has the effect of performing one rotation around an axis and then performing another rotation about around an axis.

```import numpy as np
import random

def quaternion_multiply(Q0,Q1):
"""
Multiplies two quaternions.

Input
:param Q0: A 4 element array containing the first quaternion (q01,q11,q21,q31)
:param Q1: A 4 element array containing the second quaternion (q02,q12,q22,q32)

Output
:return: A 4 element array containing the final quaternion (q03,q13,q23,q33)

"""
# Extract the values from Q0
w0 = Q0[0]
x0 = Q0[1]
y0 = Q0[2]
z0 = Q0[3]

# Extract the values from Q1
w1 = Q1[0]
x1 = Q1[1]
y1 = Q1[2]
z1 = Q1[3]

# Computer the product of the two quaternions, term by term
Q0Q1_w = w0 * w1 - x0 * x1 - y0 * y1 - z0 * z1
Q0Q1_x = w0 * x1 + x0 * w1 + y0 * z1 - z0 * y1
Q0Q1_y = w0 * y1 - x0 * z1 + y0 * w1 + z0 * x1
Q0Q1_z = w0 * z1 + x0 * y1 - y0 * x1 + z0 * w1

# Create a 4 element array containing the final quaternion
final_quaternion = np.array([Q0Q1_w, Q0Q1_x, Q0Q1_y, Q0Q1_z])

# Return a 4 element array containing the final quaternion (q02,q12,q22,q32)
return final_quaternion

Q0 = np.random.rand(4) # First quaternion
Q1 = np.random.rand(4) # Second quaternion
Q = quaternion_multiply(Q0, Q1)
print("{0} x {1} = {2}".format(Q0, Q1, Q))
```
{"found_math": false, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 0, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "url": "https://automaticaddison.com/how-to-multiply-two-quaternions-together-using-python/", "fetch_time": 1726530283000000000, "content_mime_type": "text/html", "warc_filename": "crawl-data/CC-MAIN-2024-38/segments/1725700651714.51/warc/CC-MAIN-20240916212424-20240917002424-00541.warc.gz", "warc_record_offset": 98535202, "warc_record_length": 11538, "token_count": 492, "char_count": 1415, "score": 3.625, "int_score": 4, "crawl": "CC-MAIN-2024-38", "snapshot_type": "latest", "language": "en", "language_score": 0.5106385350227356, "file_path": "/sailhome/yjruan/project/latent-lm/data/processed/finemath-4plus/finemath-4plus/train-00028-of-00064.parquet"}