Skip to content

Instantly share code, notes, and snippets.

@st98
Last active August 29, 2015 14:22
Show Gist options
  • Save st98/214499d2d48b17b0b3b2 to your computer and use it in GitHub Desktop.
Save st98/214499d2d48b17b0b3b2 to your computer and use it in GitHub Desktop.
class Complex
constructor: (re=0, im=0) ->
if not(this instanceof Complex)
return new Complex re, im
this.re = re
this.im = im
conjugate: (other) ->
new Complex @re, -@im
add: (other) ->
[re, im] = [@re + other.re, @im + other.im]
new Complex re, im
sub: (other)->
@add new Complex(-other.re, -other.im)
mul: (other) ->
[re, im] = [@re * other.re - @im * other.im, @im * other.re + @re * other.im]
new Complex re, im
div: (other) ->
re = (@re * other.re + @im * other.im) / (other.re * other.re + other.im * other.im)
im = (@im * other.re - @re * other.im) / (other.re * other.re + other.im * other.im)
new Complex re, im
toString: (other) ->
@re + '+' + @im + 'i'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment