Skip to content

Instantly share code, notes, and snippets.

@tlehman
Created February 26, 2012 20:09
Show Gist options
  • Select an option

  • Save tlehman/1918760 to your computer and use it in GitHub Desktop.

Select an option

Save tlehman/1918760 to your computer and use it in GitHub Desktop.
ComplexNumber data type
class ComplexNumber
attr_accessor :re, :im
def initialize(re, im)
# when ComplexNumber.new is called, initialize
# is run after the object is instantiated
@re = re
@im = im
end
def +(z)
sum = ComplexNumber.new @re + z.re, @im + z.im
end
def *(z)
prod = ComplexNumber.new @re*z.re - @im*z.im, @im*z.re + @re*z.im
end
def conjugate
# complex conjugate
cong = ComplexNumber.new @re, -@im
end
def to_s
# the to_s function outputs a string automatically, for example:
# suppose z is an object of type ComplexNumber, then
# puts z will implicitly call z.to_s and then output the result
output = ""
if @im >= 0
output = "#{@re} + #{@im}i"
else
output = "#{@re} - #{-1*@im}i"
end
output # return the string
end
end
# example usage of ComplexNumber objects
w = ComplexNumber.new -1, -1 # => -1 - 1i
z = ComplexNumber.new 3, 1 # => 3 + 1i
puts "w + z = #{w + z}" # => 2 + 0i
puts "w * z = #{w * z}" # => -2 - 4i
puts "the complex conjugate of #{w} is #{w.conjugate}"
puts "the product of a complex number and it's conjugate is always real:"
puts "\tw * w.conjugate = #{w*w.conjugate}"
puts "\tz * z.conjugate = #{z*z.conjugate}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment