| 1 |
class Complex < Numeric |
| 2 |
def self.polar(abs, arg = 0) |
| 3 |
Complex(abs * Math.cos(arg), abs * Math.sin(arg)) |
| 4 |
end |
| 5 |
|
| 6 |
def inspect |
| 7 |
"(#{to_s})" |
| 8 |
end |
| 9 |
|
| 10 |
def to_s |
| 11 |
"#{real}#{'+' unless imaginary < 0}#{imaginary}#{'*' unless imaginary.finite?}i" |
| 12 |
end |
| 13 |
|
| 14 |
def +@ |
| 15 |
self |
| 16 |
end |
| 17 |
|
| 18 |
def -@ |
| 19 |
Complex(-real, -imaginary) |
| 20 |
end |
| 21 |
|
| 22 |
def abs |
| 23 |
Math.hypot imaginary, real |
| 24 |
end |
| 25 |
alias_method :magnitude, :abs |
| 26 |
|
| 27 |
def abs2 |
| 28 |
real * real + imaginary * imaginary |
| 29 |
end |
| 30 |
|
| 31 |
def arg |
| 32 |
Math.atan2 imaginary, real |
| 33 |
end |
| 34 |
alias_method :angle, :arg |
| 35 |
alias_method :phase, :arg |
| 36 |
|
| 37 |
def conjugate |
| 38 |
Complex(real, -imaginary) |
| 39 |
end |
| 40 |
alias_method :conj, :conjugate |
| 41 |
|
| 42 |
def fdiv(numeric) |
| 43 |
Complex(real / numeric, imaginary / numeric) |
| 44 |
end |
| 45 |
|
| 46 |
def polar |
| 47 |
[abs, arg] |
| 48 |
end |
| 49 |
|
| 50 |
def real? |
| 51 |
false |
| 52 |
end |
| 53 |
|
| 54 |
def rectangular |
| 55 |
[real, imaginary] |
| 56 |
end |
| 57 |
alias_method :rect, :rectangular |
| 58 |
|
| 59 |
def to_c |
| 60 |
self |
| 61 |
end |
| 62 |
|
| 63 |
def to_r |
| 64 |
raise RangeError.new "can't convert #{to_s} into Rational" unless imaginary.zero? |
| 65 |
Rational(real, 1) |
| 66 |
end |
| 67 |
|
| 68 |
alias_method :imag, :imaginary |
| 69 |
|
| 70 |
Numeric.class_eval do |
| 71 |
def i |
| 72 |
Complex(0, self) |
| 73 |
end |
| 74 |
end |
| 75 |
undef i |
| 76 |
end |
| 77 |
|
| 78 |
class Numeric |
| 79 |
def to_c |
| 80 |
Complex(self, 0) |
| 81 |
end |
| 82 |
end |