Skip to content

Instantly share code, notes, and snippets.

@klgraham
Created September 7, 2012 04:05
Show Gist options
  • Save klgraham/3662997 to your computer and use it in GitHub Desktop.
Save klgraham/3662997 to your computer and use it in GitHub Desktop.
Complex arithmetic with Scala
import math.sqrt
class Complex (val real: Double, val imag: Double) {
def +(that: Complex): Complex = new Complex(this.real + that.real, this.imag + that.imag)
def -(that: Complex): Complex = new Complex(this.real - that.real, this.imag - that.imag)
val mod = (z: Complex) => math.sqrt(z.real * z.real + z.imag * z.imag)
def *(that: Complex): Complex = {
val real = this.real * that.real - this.imag * that.imag
val imag = this.real * that.imag + this.imag * that.real
new Complex(real, imag)
}
def /(that: Complex): Complex = {
val real = this.real * that.real + this.imag * that.imag
val imag = this.imag * that.real - this.real * that.imag
val denom = mod(that)
new Complex(real / denom, imag / denom)
}
def *(scalar: Double): Complex = new Complex(this.real * scalar, this.imag * scalar)
def /(scalar: Double): Complex = new Complex(this.real / scalar, this.imag / scalar)
override def toString(): String = "Complex(" + this.real + ", " + this.imag + ")"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment