Created
February 26, 2012 20:09
-
-
Save tlehman/1918760 to your computer and use it in GitHub Desktop.
ComplexNumber data type
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
| 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