1 class Complex < Numeric
2 def self.polar(abs, arg = 0)
3 Complex(abs * Math.cos(arg), abs * Math.sin(arg))
11 "#{real}#{'+' unless imaginary < 0}#{imaginary}i"
15 Complex(real, imaginary)
19 Complex(-real, -imaginary)
24 Complex(real + rhs.real, imaginary + rhs.imaginary)
25 elsif rhs.is_a? Numeric
26 Complex(real + rhs, imaginary)
32 Complex(real - rhs.real, imaginary - rhs.imaginary)
33 elsif rhs.is_a? Numeric
34 Complex(real - rhs, imaginary)
40 Complex(real * rhs.real - imaginary * rhs.imaginary, real * rhs.imaginary + rhs.real * imaginary)
41 elsif rhs.is_a? Numeric
42 Complex(real * rhs, imaginary * rhs)
49 elsif rhs.is_a? Numeric
50 Complex(real / rhs, imaginary / rhs)
57 real == rhs.real && imaginary == rhs.imaginary
58 elsif rhs.is_a? Numeric
59 imaginary == 0 && real == rhs
64 Math.hypot imaginary, real
66 alias_method :magnitude, :abs
69 real * real + imaginary * imaginary
73 Math.atan2 imaginary, real
75 alias_method :angle, :arg
76 alias_method :phase, :arg
79 Complex(real, -imaginary)
81 alias_method :conj, :conjugate
84 Complex(real.to_f / numeric, imaginary.to_f / numeric)
98 alias_method :rect, :rectangular
101 raise RangeError.new "can't convert #{to_s} into Rational" unless imaginary.zero?
105 alias_method :imag, :imaginary
107 [Fixnum, Float].each do |cls|
108 [:+, :-, :*, :/, :==].each do |op|
110 original_operator_name = :"__original_operator_#{op}_complex"
111 alias_method original_operator_name, op
112 define_method op do |rhs|
114 Complex(self).__send__(op, rhs)
116 __send__(original_operator_name, rhs)