CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-pyquaternion

A fully featured, pythonic library for quaternion representation, manipulation, 3D animation and geometry.

Pending
Overview
Eval results
Files

basic-operations.mddocs/

Basic Operations

Fundamental quaternion operations including arithmetic, comparison, normalization, type conversion, and component access.

Capabilities

Arithmetic Operations

Standard mathematical operations with proper quaternion algebra.

def __add__(self, other):
    """
    Add two quaternions element-wise.
    
    Parameters:
        other: Quaternion or scalar
    
    Returns:
        Quaternion: Sum of quaternions
    """

def __sub__(self, other):
    """
    Subtract quaternions element-wise.
    
    Parameters:
        other: Quaternion or scalar
    
    Returns:
        Quaternion: Difference of quaternions
    """

def __mul__(self, other):
    """
    Multiply quaternions using quaternion product (non-commutative).
    
    Parameters:
        other: Quaternion or scalar
    
    Returns:
        Quaternion: Product of quaternions
    """

def __div__(self, other):
    """
    Divide quaternions by multiplying with inverse.
    
    Parameters:
        other: Quaternion or scalar (non-zero)
    
    Returns:
        Quaternion: Quotient of quaternions
    
    Raises:
        ZeroDivisionError: If divisor is zero quaternion
    """

def __pow__(self, exponent):
    """
    Raise quaternion to a power using polar decomposition.
    
    Parameters:
        exponent: float, real-valued exponent
    
    Returns:
        Quaternion: Quaternion raised to the power
    """

Usage Examples:

from pyquaternion import Quaternion

q1 = Quaternion(1, 0, 0, 0)
q2 = Quaternion(0, 1, 0, 0)

# Basic arithmetic
sum_q = q1 + q2          # Element-wise addition
diff_q = q1 - q2         # Element-wise subtraction
product_q = q1 * q2      # Quaternion multiplication (non-commutative)
quotient_q = q1 / q2     # Division via inverse
power_q = q1 ** 2        # Exponentiation

# Scalar operations
scaled_q = q1 * 2.0      # Scalar multiplication
divided_q = q1 / 2.0     # Scalar division

In-place Operations

Modify quaternions in-place for efficient computation.

def __iadd__(self, other):
    """In-place addition."""

def __isub__(self, other):
    """In-place subtraction."""

def __imul__(self, other):
    """In-place multiplication."""

def __idiv__(self, other):
    """In-place division."""

def __ipow__(self, other):
    """In-place exponentiation."""

Unary Operations

def __neg__(self):
    """
    Negate all quaternion components.
    
    Returns:
        Quaternion: Negated quaternion (-w, -x, -y, -z)
    """

def __abs__(self):
    """
    Get the norm (magnitude) of the quaternion.
    
    Returns:
        float: L2 norm of quaternion 4-vector
    """

Matrix Operations

Support for matrix multiplication operator (@).

def __matmul__(self, other):
    """
    Matrix multiplication (@ operator) - computes dot product of quaternion arrays.
    
    Parameters:
        other: Quaternion
    
    Returns:
        float: Dot product of quaternion 4-vectors
    """

Comparison Operations

def __eq__(self, other):
    """
    Test equality with tolerance.
    
    Uses numpy.allclose with rtol=1e-13, atol=1e-14
    
    Parameters:
        other: Quaternion or convertible type
    
    Returns:
        bool: True if quaternions are equal within tolerance
    """

def __hash__(self):
    """
    Hash support for use in sets and dictionaries.
    
    Returns:
        int: Hash of quaternion tuple
    """

Utility Methods

Static methods for angle conversion and quaternion validation.

@staticmethod
def to_degrees(angle_rad):
    """
    Convert radians to degrees.
    
    Parameters:
        angle_rad: float, angle in radians
    
    Returns:
        float: Angle in degrees
    """

@staticmethod
def to_radians(angle_deg):
    """
    Convert degrees to radians.
    
    Parameters:
        angle_deg: float, angle in degrees
    
    Returns:
        float: Angle in radians
    """

def is_unit(self, tolerance=1e-14):
    """
    Check if quaternion is a unit quaternion (within tolerance).
    
    Parameters:
        tolerance: float, tolerance for unit length check
    
    Returns:
        bool: True if |norm - 1| < tolerance
    """

Usage Examples:

from pyquaternion import Quaternion
import math

# Angle conversion
degrees = Quaternion.to_degrees(math.pi)  # 180.0
radians = Quaternion.to_radians(90)       # 1.5707963267948966

# Unit quaternion check
q = Quaternion(axis=[0, 1, 0], degrees=90)
print(q.is_unit())  # True

q_scaled = q * 2.0
print(q_scaled.is_unit())  # False

Core Properties

Essential quaternion properties for mathematical operations.

@property
def conjugate(self):
    """
    Quaternion conjugate (vector part negated).
    
    For unit quaternions, this equals the inverse.
    
    Returns:
        Quaternion: New quaternion with negated vector part (w, -x, -y, -z)
    """

@property
def inverse(self):
    """
    Quaternion inverse for non-zero quaternions.
    
    For unit quaternions, this is the inverse rotation.
    
    Returns:
        Quaternion: Multiplicative inverse
    
    Raises:
        ZeroDivisionError: If quaternion is zero (0, 0, 0, 0)
    """

@property
def norm(self):
    """
    L2 norm (magnitude) of quaternion 4-vector.
    
    Should be 1.0 for unit quaternions (versors).
    
    Returns:
        float: sqrt(w² + x² + y² + z²)
    """

@property
def magnitude(self):
    """Alias for norm."""

@property
def normalised(self):
    """
    Get unit quaternion copy.
    
    Returns:
        Quaternion: New quaternion with norm = 1.0
    """

@property
def unit(self):
    """Alias for normalised."""

Normalization Methods

def is_unit(self, tolerance=1e-14):
    """
    Check if quaternion is of unit length.
    
    Parameters:
        tolerance: Maximum deviation from unit length
    
    Returns:
        bool: True if |norm - 1| < tolerance
    """

def _normalise(self):
    """
    Normalize quaternion in-place to unit length.
    
    Modifies the quaternion object directly.
    No effect if quaternion is zero.
    """

def _fast_normalise(self):
    """
    Fast in-place normalization using approximation when appropriate.
    
    Uses Padé approximation for small errors, full sqrt otherwise.
    """

Usage Examples:

q = Quaternion(2, 0, 0, 0)

# Check and normalize
print(f"Is unit: {q.is_unit()}")     # False
print(f"Norm: {q.norm}")             # 2.0

# Get normalized copy
unit_q = q.normalised
print(f"Original: {q}")              # (2, 0, 0, 0)
print(f"Normalized: {unit_q}")       # (1, 0, 0, 0)

# In-place normalization
q._normalise()
print(f"After normalize: {q}")       # (1, 0, 0, 0)

Type Conversion

Convert quaternions to other Python types.

def __int__(self):
    """
    Convert to int using only the real component.
    
    Returns:
        int: Truncated real component
    """

def __float__(self):
    """
    Convert to float using only the real component.
    
    Returns:
        float: Real component as float
    """

def __complex__(self):
    """
    Convert to complex using real and first imaginary components.
    
    Returns:
        complex: complex(w, x)
    """

def __bool__(self):
    """
    Boolean conversion - True if non-zero quaternion.
    
    Returns:
        bool: False only for zero quaternion (0, 0, 0, 0)
    """

Component Access

Access individual quaternion components.

@property
def scalar(self):
    """Real/scalar component (w)."""

@property
def vector(self):
    """Imaginary/vector components as numpy array [x, y, z]."""

@property
def real(self):
    """Alias for scalar."""

@property
def imaginary(self):
    """Alias for vector."""

@property
def w(self):
    """Scalar component."""

@property
def x(self):
    """First vector component."""

@property
def y(self):
    """Second vector component."""

@property
def z(self):
    """Third vector component."""

@property
def elements(self):
    """All quaternion elements as numpy array [w, x, y, z]."""

def __getitem__(self, index):
    """Get component by index (0=w, 1=x, 2=y, 3=z)."""

def __setitem__(self, index, value):
    """Set component by index (0=w, 1=x, 2=y, 3=z)."""

String Representation

def __str__(self):
    """
    Informal string representation.
    
    Returns:
        str: Format like "1.000 +0.000i +0.000j +0.000k"
    """

def __repr__(self):
    """
    Official string representation for debugging.
    
    Returns:
        str: Valid Python expression to recreate quaternion
    """

def __format__(self, formatstr):
    """
    Custom formatting support.
    
    Parameters:
        formatstr: Format specification (follows float format rules)
    
    Returns:
        str: Formatted quaternion string
    """

Copy Operations

def __copy__(self):
    """Shallow copy support."""

def __deepcopy__(self, memo):
    """Deep copy support with memo dict."""

Install with Tessl CLI

npx tessl i tessl/pypi-pyquaternion

docs

advanced-math.md

basic-operations.md

construction.md

index.md

interpolation.md

rotation.md

tile.json