Class: Complex

Inherits:
Numeric show all
Defined in:
opal/opal/corelib/complex.rb

Constant Summary collapse

I =
new(0, 1)

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Numeric

#%, #+@, #<=>, #__coerced__, #ceil, #clone, #div, #divmod, #dup, #floor, #i, #integer?, #negative?, #nonzero?, #positive?, #round, #step, #to_c, #to_int, #truncate, #zero?

Methods included from Comparable

#<, #<=, #>, #>=, #between?, #clamp

Constructor Details

#initialize(real, imag = 0) ⇒ Complex

Returns a new instance of Complex.



23
24
25
26
27
# File 'opal/opal/corelib/complex.rb', line 23

def initialize(real, imag = 0)
  @real = real
  @imag = imag
  freeze
end

Instance Attribute Details

#imagObject (readonly) Also known as: imaginary

Returns the value of attribute imag.



21
22
23
# File 'opal/opal/corelib/complex.rb', line 21

def imag
  @imag
end

#realObject (readonly)

Returns the value of attribute real.



21
22
23
# File 'opal/opal/corelib/complex.rb', line 21

def real
  @real
end

Class Method Details

.from_string(str) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'opal/opal/corelib/complex.rb', line 271

def self.from_string(str)
  %x{
    var re = /[+-]?[\d_]+(\.[\d_]+)?(e\d+)?/,
        match = str.match(re),
        real, imag, denominator;

    function isFloat() {
      return re.test(str);
    }

    function cutFloat() {
      var match = str.match(re);
      var number = match[0];
      str = str.slice(number.length);
      return number.replace(/_/g, '');
    }

    // handles both floats and rationals
    function cutNumber() {
      if (isFloat()) {
        var numerator = parseFloat(cutFloat());

        if (str[0] === '/') {
          // rational real part
          str = str.slice(1);

          if (isFloat()) {
            var denominator = parseFloat(cutFloat());
            return #{::Kernel.Rational(`numerator`, `denominator`)};
          } else {
            // reverting '/'
            str = '/' + str;
            return numerator;
          }
        } else {
          // float real part, no denominator
          return numerator;
        }
      } else {
        return null;
      }
    }

    real = cutNumber();

    if (!real) {
      if (str[0] === 'i') {
        // i => Complex(0, 1)
        return #{::Kernel.Complex(0, 1)};
      }
      if (str[0] === '-' && str[1] === 'i') {
        // -i => Complex(0, -1)
        return #{::Kernel.Complex(0, -1)};
      }
      if (str[0] === '+' && str[1] === 'i') {
        // +i => Complex(0, 1)
        return #{::Kernel.Complex(0, 1)};
      }
      // anything => Complex(0, 0)
      return #{::Kernel.Complex(0, 0)};
    }

    imag = cutNumber();
    if (!imag) {
      if (str[0] === 'i') {
        // 3i => Complex(0, 3)
        return #{::Kernel.Complex(0, `real`)};
      } else {
        // 3 => Complex(3, 0)
        return #{::Kernel.Complex(`real`, 0)};
      }
    } else {
      // 3+2i => Complex(3, 2)
      return #{::Kernel.Complex(`real`, `imag`)};
    }
  }
end

.polar(r, theta = 0) ⇒ Object



13
14
15
16
17
18
19
# File 'opal/opal/corelib/complex.rb', line 13

def self.polar(r, theta = 0)
  unless ::Numeric === r && r.real? && ::Numeric === theta && theta.real?
    ::Kernel.raise ::TypeError, 'not a real'
  end

  new(r * ::Math.cos(theta), r * ::Math.sin(theta))
end

.rect(real, imag = 0) ⇒ Object Also known as: rectangular



5
6
7
8
9
10
11
# File 'opal/opal/corelib/complex.rb', line 5

def self.rect(real, imag = 0)
  unless ::Numeric === real && real.real? && ::Numeric === imag && imag.real?
    ::Kernel.raise ::TypeError, 'not a real'
  end

  new(real, imag)
end

Instance Method Details

#*(other) ⇒ Object



73
74
75
76
77
78
79
80
81
82
83
# File 'opal/opal/corelib/complex.rb', line 73

def *(other)
  if ::Complex === other
    ::Kernel.Complex(@real * other.real - @imag * other.imag,
      @real * other.imag + @imag * other.real,
    )
  elsif ::Numeric === other && other.real?
    ::Kernel.Complex(@real * other, @imag * other)
  else
    __coerced__ :*, other
  end
end

#**(other) ⇒ Object



100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'opal/opal/corelib/complex.rb', line 100

def **(other)
  if other == 0
    return ::Complex.new(1, 0)
  end

  if ::Complex === other
    r, theta = polar
    ore      = other.real
    oim      = other.imag
    nr       = ::Math.exp(ore * ::Math.log(r) - oim * theta)
    ntheta   = theta * ore + oim * ::Math.log(r)

    ::Complex.polar(nr, ntheta)
  elsif ::Integer === other
    if other > 0
      x = self
      z = x
      n = other - 1

      while n != 0
        div, mod = n.divmod(2)
        while mod == 0
          x = ::Kernel.Complex(x.real * x.real - x.imag * x.imag, 2 * x.real * x.imag)
          n = div
          div, mod = n.divmod(2)
        end

        z *= x
        n -= 1
      end

      z
    else
      (::Rational.new(1, 1) / self)**-other
    end
  elsif ::Float === other || ::Rational === other
    r, theta = polar

    ::Complex.polar(r**other, theta * other)
  else
    __coerced__ :**, other
  end
end

#+(other) ⇒ Object



53
54
55
56
57
58
59
60
61
# File 'opal/opal/corelib/complex.rb', line 53

def +(other)
  if ::Complex === other
    ::Kernel.Complex(@real + other.real, @imag + other.imag)
  elsif ::Numeric === other && other.real?
    ::Kernel.Complex(@real + other, @imag)
  else
    __coerced__ :+, other
  end
end

#-(other) ⇒ Object



63
64
65
66
67
68
69
70
71
# File 'opal/opal/corelib/complex.rb', line 63

def -(other)
  if ::Complex === other
    ::Kernel.Complex(@real - other.real, @imag - other.imag)
  elsif ::Numeric === other && other.real?
    ::Kernel.Complex(@real - other, @imag)
  else
    __coerced__ :-, other
  end
end

#-@Object



49
50
51
# File 'opal/opal/corelib/complex.rb', line 49

def -@
  ::Kernel.Complex(-@real, -@imag)
end

#/(other) ⇒ Object Also known as: divide, quo



85
86
87
88
89
90
91
92
93
94
95
96
97
98
# File 'opal/opal/corelib/complex.rb', line 85

def /(other)
  if ::Complex === other
    if (::Number === @real && @real.nan?) || (::Number === @imag && @imag.nan?) ||
       (::Number === other.real && other.real.nan?) || (::Number === other.imag && other.imag.nan?)
      ::Complex.new(::Float::NAN, ::Float::NAN)
    else
      self * other.conj / other.abs2
    end
  elsif ::Numeric === other && other.real?
    ::Kernel.Complex(@real.quo(other), @imag.quo(other))
  else
    __coerced__ :/, other
  end
end

#==(other) ⇒ Object



39
40
41
42
43
44
45
46
47
# File 'opal/opal/corelib/complex.rb', line 39

def ==(other)
  if ::Complex === other
    @real == other.real && @imag == other.imag
  elsif ::Numeric === other && other.real?
    @real == other && @imag == 0
  else
    other == self
  end
end

#absObject Also known as: magnitude



144
145
146
# File 'opal/opal/corelib/complex.rb', line 144

def abs
  ::Math.hypot(@real, @imag)
end

#abs2Object



148
149
150
# File 'opal/opal/corelib/complex.rb', line 148

def abs2
  @real * @real + @imag * @imag
end

#angleObject Also known as: arg



152
153
154
# File 'opal/opal/corelib/complex.rb', line 152

def angle
  ::Math.atan2(@imag, @real)
end

#coerce(other) ⇒ Object



29
30
31
32
33
34
35
36
37
# File 'opal/opal/corelib/complex.rb', line 29

def coerce(other)
  if ::Complex === other
    [other, self]
  elsif ::Numeric === other && other.real?
    [::Complex.new(other, 0), self]
  else
    ::Kernel.raise ::TypeError, "#{other.class} can't be coerced into Complex"
  end
end

#conjObject Also known as: conjugate



156
157
158
# File 'opal/opal/corelib/complex.rb', line 156

def conj
  ::Kernel.Complex(@real, -@imag)
end

#denominatorObject



160
161
162
# File 'opal/opal/corelib/complex.rb', line 160

def denominator
  @real.denominator.lcm(@imag.denominator)
end

#eql?(other) ⇒ Boolean

Returns:



164
165
166
# File 'opal/opal/corelib/complex.rb', line 164

def eql?(other)
  Complex === other && @real.class == @imag.class && self == other
end

#fdiv(other) ⇒ Object



168
169
170
171
172
173
174
# File 'opal/opal/corelib/complex.rb', line 168

def fdiv(other)
  unless ::Numeric === other
    ::Kernel.raise ::TypeError, "#{other.class} can't be coerced into Complex"
  end

  self / other
end

#finite?Boolean

Returns:



176
177
178
# File 'opal/opal/corelib/complex.rb', line 176

def finite?
  @real.finite? && @imag.finite?
end

#hashObject



180
181
182
# File 'opal/opal/corelib/complex.rb', line 180

def hash
  "Complex:#{@real}:#{@imag}"
end

#infinite?Boolean

Returns:



184
185
186
# File 'opal/opal/corelib/complex.rb', line 184

def infinite?
  @real.infinite? || @imag.infinite?
end

#inspectObject



188
189
190
# File 'opal/opal/corelib/complex.rb', line 188

def inspect
  "(#{self})"
end

#numeratorObject



192
193
194
195
196
197
198
# File 'opal/opal/corelib/complex.rb', line 192

def numerator
  d = denominator

  ::Kernel.Complex(@real.numerator * (d / @real.denominator),
    @imag.numerator * (d / @imag.denominator),
  )
end

#polarObject



200
201
202
# File 'opal/opal/corelib/complex.rb', line 200

def polar
  [abs, arg]
end

#rationalize(eps = undefined) ⇒ Object



204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'opal/opal/corelib/complex.rb', line 204

def rationalize(eps = undefined)
  %x{
    if (arguments.length > 1) {
      #{::Kernel.raise ::ArgumentError, "wrong number of arguments (#{`arguments.length`} for 0..1)"};
    }
  }

  if @imag != 0
    ::Kernel.raise ::RangeError, "can't convert #{self} into Rational"
  end

  real.rationalize(eps)
end

#real?Boolean

Returns:



218
219
220
# File 'opal/opal/corelib/complex.rb', line 218

def real?
  false
end

#rectObject Also known as: rectangular



222
223
224
# File 'opal/opal/corelib/complex.rb', line 222

def rect
  [@real, @imag]
end

#to_fObject



226
227
228
229
230
231
232
# File 'opal/opal/corelib/complex.rb', line 226

def to_f
  unless @imag == 0
    ::Kernel.raise ::RangeError, "can't convert #{self} into Float"
  end

  @real.to_f
end

#to_iObject



234
235
236
237
238
239
240
# File 'opal/opal/corelib/complex.rb', line 234

def to_i
  unless @imag == 0
    ::Kernel.raise ::RangeError, "can't convert #{self} into Integer"
  end

  @real.to_i
end

#to_rObject



242
243
244
245
246
247
248
# File 'opal/opal/corelib/complex.rb', line 242

def to_r
  unless @imag == 0
    ::Kernel.raise ::RangeError, "can't convert #{self} into Rational"
  end

  @real.to_r
end

#to_sObject



250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
# File 'opal/opal/corelib/complex.rb', line 250

def to_s
  result = @real.inspect

  result +=
    if (::Number === @imag && @imag.nan?) || @imag.positive? || @imag.zero?
      '+'
    else
      '-'
    end

  result += @imag.abs.inspect

  if ::Number === @imag && (@imag.nan? || @imag.infinite?)
    result += '*'
  end

  result + 'i'
end