Created
September 7, 2012 04:05
-
-
Save klgraham/3662997 to your computer and use it in GitHub Desktop.
Complex arithmetic with Scala
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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