Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Complex multiplication using Matrix multiplication
/* In a comment to Problem 6 of Linear Algebra Problem Book,
Halmos notes that the multiplication of complex numbers is a
special case of matrix multiplication via the representation
of complex number a + bi as the 2-by-2 matrix {{a, b}, {-b, a}}.
This is pretty nice because if we have a matrix data type with
a multiplication defined on it, we can just embed the complex
number in a matrix, multiply by another such embedding and
then extract the resulting complex number out.
The same trick works for affine transformations (Problem 5) via
the (a, b)-as-(a, b, 0, 1) representation.
*/
// -----------------
// Matrices (2 by 2)
// -----------------
function Matrix(a, b, c, d) {
this.a = a; this.b = b; this.c = c; this.d = d;
}
Matrix.prototype.mult = function(other) {
var a = (this.a * other.a) + (this.b * other.c);
var b = (this.a * other.b) + (this.b * other.d);
var c = (this.c * other.a) + (this.d * other.c);
var d = (this.c * other.b) + (this.d * other.d);
return new Matrix(a, b, c, d);
}
// Example
// -------
var m1 = new Matrix(2, 3, 4, 5);
var m2 = new Matrix(6, 7, 8, 9);
// Multiply
m1.mult(m2);
// Matrix {a: 36, b: 41, c: 64, d: 73}
// ---------------
// Complex numbers
// ---------------
function Complex(a, b) {
this.re = a; this.im = b;
}
Complex.prototype.mult = function(other) {
var re = (this.re * other.re) - (this.im * other.im);
var im = (this.re * other.im) + (this.im * other.re);
return new Complex(re, im);
}
// Example
// -------
var c1 = new Complex(2, 3);
var c2 = new Complex(-3, 5);
// Multiply using complex multiplication.
c1.mult(c2);
// Complex {re: -21, im: 1}
// ------------------------------
// Represent Complex using Matrix
// ------------------------------
// Encode a complex number as a matrix.
function Encode(c) {
return new Matrix(c.re, c.im, -c.im, c.re);
}
// Extract the complex number out of the matrix.
function Decode(m) {
return new Complex(m.a, m.b);
}
// Example
// -------
var mc1 = Encode(new Complex(2, 3)); // a Matrix
var mc2 = Encode(new Complex(-3, 5)); // a Matrix
// Multiply the complex numbers using matrix multiplication.
var result = Decode(mc1.mult(mc2)); // a Complex number
//=> Complex {re: -21, im: 1}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment