summaryrefslogtreecommitdiffhomepage
path: root/mrbgems/mruby-complex/mrblib/complex.rb
blob: 0815c9a718297b06724b5351442acfc09c244cfb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
class Complex < Numeric
  def initialize(real = 0, imaginary = 0)
    @real = real
    @imaginary = imaginary
  end

  def inspect
    "(#{to_s})"
  end

  def to_s
    "#{real}#{'+'}#{imaginary}i"
  end

  def +@
    Complex.new(real, imaginary)
  end

  def -@
    Complex.new(-real, -imaginary)
  end

  def +(rhs)
    if rhs.is_a? Complex
      Complex.new(real + rhs.real, imaginary + rhs.imaginary)
    elsif rhs.is_a? Numeric
      Complex.new(real + rhs, imaginary)
    end
  end

  def -(rhs)
    if rhs.is_a? Complex
      Complex.new(real - rhs.real, imaginary - rhs.imaginary)
    elsif rhs.is_a? Numeric
      Complex.new(real - rhs, imaginary)
    end
  end

  def *(rhs)
    if rhs.is_a? Complex
      Complex.new(real * rhs.real - imaginary * rhs.imaginary, real * rhs.imaginary + rhs.real * imaginary)
    elsif rhs.is_a? Numeric
      Complex.new(real * rhs, imaginary * rhs)
    end
  end

  def /(rhs)
    if rhs.is_a? Complex
      div = rhs.real * rhs.real + rhs.imaginary * rhs.imaginary
      Complex.new((real * rhs.real + imaginary * rhs.imaginary) / div, (rhs.real * imaginary - real * rhs.imaginary) / div)
    elsif rhs.is_a? Numeric
      Complex.new(real / rhs, imaginary / rhs)
    end
  end

  attr_reader :real, :imaginary
end

def Complex(real = 0, imaginary = 0)
  Complex.new(real, imaginary)
end

module ForwardOperatorToComplex
  def __forward_operator_to_complex(op, &b)
    original_operator_name = "__original_operator_#{op}_complex"
    alias_method original_operator_name, op
    define_method op do |rhs|
      if rhs.is_a? Complex
        Complex.new(self).send(op, rhs)
      else
        send(original_operator_name, rhs)
      end
    end
  end

  def __forward_operators_to_complex
    __forward_operator_to_complex :+
    __forward_operator_to_complex :-
    __forward_operator_to_complex :*
    __forward_operator_to_complex :/

    singleton_class.undef_method :__forward_operator_to_complex
    singleton_class.undef_method :__forward_operators_to_complex
  end
end

class Fixnum
  extend ForwardOperatorToComplex
  __forward_operators_to_complex
end

class Float
  extend ForwardOperatorToComplex
  __forward_operators_to_complex
end