make a quaternion calculator in python

To make a quaternion calculator in python, we'll first need to understand what quaternions are and how they work. Quaternions are a type of hypercomplex number that extend the complex numbers in a way that allows for rotation in three dimensions. They are represented by four real numbers: a scalar (w) and a vector (x, y, z).

We can use the NumPy library to help us with the mathematical operations involved in working with quaternions. Here is some code to help you get started with a quaternion class in python:

main.py
import numpy as np

class Quaternion:
    
    def __init__(self, scalar, x, y, z):
        self.scalar = scalar
        self.vector = np.array([x, y, z])
    
    def __repr__(self):
        return f'{self.scalar} + {self.vector[0]}i + {self.vector[1]}j + {self.vector[2]}k'
    
    def __add__(self, other):
        return Quaternion(self.scalar + other.scalar, self.vector[0] + other.vector[0], self.vector[1] + other.vector[1], self.vector[2] + other.vector[2])
    
    def __sub__(self, other):
        return Quaternion(self.scalar - other.scalar, self.vector[0] - other.vector[0], self.vector[1] - other.vector[1], self.vector[2] - other.vector[2])
    
    def __mul__(self, other):
        if isinstance(other, Quaternion):
            scalar = self.scalar * other.scalar - np.dot(self.vector, other.vector)
            vector = self.scalar * other.vector + other.scalar * self.vector + np.cross(self.vector, other.vector)
            return Quaternion(scalar, vector[0], vector[1], vector[2])
        else:
            return Quaternion(other * self.scalar, other * self.vector[0], other * self.vector[1], other * self.vector[2])
    
    def __rmul__(self, other):
        return self.__mul__(other)
1213 chars
28 lines

Now that we have a Quaternion class, we can perform basic arithmetic operations like addition, subtraction and multiplication using the "+" "-" and "*" operator respectively.

main.py
q1 = Quaternion(1, 2, 3, 4)
q2 = Quaternion(5, 6, 7, 8)
print(q1 + q2)  # prints 6.0 + 8.0i + 10.0j + 12.0k
print(q1 - q2)  # prints -4.0 - 4.0i - 4.0j - 4.0k
print(q1 * q2)  # prints -60.0 + 12.0i + 30.0j + 24.0k
print(q1 * 2)   # prints 2.0 + 4.0i + 6.0j + 8.0k
264 chars
7 lines

With this basic setup, you can continue to expand the functionalities of the quaternion calculator!

gistlibby LogSnag