Skip to content

Instantly share code, notes, and snippets.

@gubatron
Created April 14, 2022 17:46
Show Gist options
  • Save gubatron/c9685c6809e2be5d6e89e640c540f50f to your computer and use it in GitHub Desktop.
Save gubatron/c9685c6809e2be5d6e89e640c540f50f to your computer and use it in GitHub Desktop.
Class to represent a Complex number and a few operations that can be done with them
class Complex {
constructor(real, imag) {
this.real = real
this.imag = imag
}
length() {
return Math.sqrt(this.real * this.real + this.imag * this.imag)
}
mul(other) {
// first outers inners lasts
// (aR+aI)(bR+bI) = aR * bR +
// aR * bI +
// aI * bR +
// aI * bI => -a*b
//
return new Complex(this.real * other.real - this.imag * other.imag,
this.real * other.imag + this.imag * other.real)
}
add(other) {
return new Complex(this.real + other.real, this.imag + other.imag)
}
square() {
return this.mul(this)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment