# LinAlg API: 4D Math with Quaternions

Posted by aschunkjava on December 13, 2007 at 5:12 AM PST

## 4D Math with Quaternions

LinALg API now provides 4D Math operations using Quaternions. For those that are not familiar with Quaternions i will provide a short introduction.

## What are Quaternions?

A Quaternion is a 4 dimensional number consisting of a real part and three imaginary parts thus a Quaternion can be written as:

``xo + x1 * i + x2 * j + x3 * k;``

In this case, the constants i, j and k and their factors represent the imaginary part of a Quaternion. If you are familiar with complex numbers you now that the square root of i^2 = -1. This equation is also valid for the three other imaginary parts of quaternion that is i^2 = j^2 = k^2 = -1. There are some other rules that apply to the imaginary parts of Quaternions i.g. i * j = k and j * i = -k yet these are not important for this Blog but for the understanding of Quaternion theory.

## Basic operations

As with complex numbers there are basic operations for +,-*,/, complex conjugate and scalar multiplication for Quaternions. Again, as with complex numbers or Vectors, the sum, difference and product of Quaternions are per component operations that is you add or subtract over each component of a Quaternion.

## When are Quaternions useful?

Quaternions are used in 3D Math to describe a rotation of an object in 3D space using a simple scalar and a 3D Vector so a Quaternion can be written as follows: [s, v] where s is a normal scalar and v is a Vector with components x,y,z.

You can do the same using matrices to describe a rotation or translation but with Quaternions you need less memory for the operations so Quaternions are used to safe memory and gain speed.

## A Java Implementation for Quaternions

A Java Implementation for Quaternions should represent the fact that a Quaternion is a 4D space number with four elements - that is the scalar and the three imaginary parts - and provide basic operations on Quaternions. So a basic Java Quaternion type might look like this:

``public class Quaternion{ private double s, x, y, z; //scalar, x, y and z coordinates public Quaternion(double s, double x, double y, double z){    //basic construction   } //creates an identity quaternion with s = 1 public Quaternion identity(){    this.s = 1;    this.x = 0;    this.y = 0;    this.z = 0; } public Quaternion add(Quaternion q){}; public Quaternion sub(Quaternion q){}; public Quaternion mul(Quaternion q){}; public Quaternion conjugate(){};}``

The Quaternion used in LinAlg API already provides basic methods for +, conjugation, -, negation and construction. Whats missing is * and the possibility to create Quaternions from Euler angles and to create a rotation matrix for Quaternions.