Class: Rational

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

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Numeric

#%, #+@, #-@, #__coerced__, #abs2, #angle, #clone, #conj, #div, #divmod, #dup, #fdiv, #finite?, #i, #imag, #infinite?, #integer?, #negative?, #nonzero?, #polar, #positive?, #real, #real?, #rect, #step, #to_c, #to_int, #zero?

Methods included from Comparable

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

Constructor Details

#initialize(num, den) ⇒ Rational

Returns a new instance of Rational.



51
52
53
54
55
# File 'opal/opal/corelib/rational.rb', line 51

def initialize(num, den)
  @num = num
  @den = den
  freeze
end

Class Method Details

.convert(num, den) ⇒ Object



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
# File 'opal/opal/corelib/rational.rb', line 25

def self.convert(num, den)
  if num.nil? || den.nil?
    ::Kernel.raise ::TypeError, 'cannot convert nil into Rational'
  end

  if ::Integer === num && ::Integer === den
    return reduce(num, den)
  end

  if ::Float === num || ::String === num || ::Complex === num
    num = num.to_r
  end

  if ::Float === den || ::String === den || ::Complex === den
    den = den.to_r
  end

  if den.equal?(1) && !(::Integer === num)
    ::Opal.coerce_to!(num, ::Rational, :to_r)
  elsif ::Numeric === num && ::Numeric === den
    num / den
  else
    reduce(num, den)
  end
end

.from_string(string) ⇒ Object



354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'opal/opal/corelib/rational.rb', line 354

def self.from_string(string)
  %x{
    var str = string.trimLeft(),
        re = /^[+-]?[\d_]+(\.[\d_]+)?/,
        match = str.match(re),
        numerator, 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, '');
    }

    if (isFloat()) {
      numerator = parseFloat(cutFloat());

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

        if (isFloat()) {
          denominator = parseFloat(cutFloat());
          return #{::Kernel.Rational(`numerator`, `denominator`)};
        } else {
          return #{::Kernel.Rational(`numerator`, 1)};
        }
      } else {
        return #{::Kernel.Rational(`numerator`, 1)};
      }
    } else {
      return #{::Kernel.Rational(0, 1)};
    }
  }
end

.reduce(num, den) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'opal/opal/corelib/rational.rb', line 7

def self.reduce(num, den)
  num = num.to_i
  den = den.to_i

  if den == 0
    ::Kernel.raise ::ZeroDivisionError, 'divided by 0'
  elsif den < 0
    num = -num
    den = -den
  elsif den == 1
    return new(num, den)
  end

  gcd = num.gcd(den)

  new(num / gcd, den / gcd)
end

Instance Method Details

#*(other) ⇒ Object



148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'opal/opal/corelib/rational.rb', line 148

def *(other)
  case other
  when ::Rational
    num = @num * other.numerator
    den = @den * other.denominator

    ::Kernel.Rational(num, den)

  when ::Integer
    ::Kernel.Rational(@num * other, @den)

  when ::Float
    to_f * other

  else
    __coerced__ :*, other
  end
end

#**(other) ⇒ Object



190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'opal/opal/corelib/rational.rb', line 190

def **(other)
  case other
  when ::Integer
    if self == 0 && other < 0
      ::Float::INFINITY
    elsif other > 0
      ::Kernel.Rational(@num**other, @den**other)
    elsif other < 0
      ::Kernel.Rational(@den**-other, @num**-other)
    else
      ::Kernel.Rational(1, 1)
    end

  when ::Float
    to_f**other

  when ::Rational
    if other == 0
      ::Kernel.Rational(1, 1)
    elsif other.denominator == 1
      if other < 0
        ::Kernel.Rational(@den**other.numerator.abs, @num**other.numerator.abs)
      else
        ::Kernel.Rational(@num**other.numerator, @den**other.numerator)
      end
    elsif self == 0 && other < 0
      ::Kernel.raise ::ZeroDivisionError, 'divided by 0'
    else
      to_f**other
    end

  else
    __coerced__ :**, other
  end
end

#+(other) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
# File 'opal/opal/corelib/rational.rb', line 110

def +(other)
  case other
  when ::Rational
    num = @num * other.denominator + @den * other.numerator
    den = @den * other.denominator

    ::Kernel.Rational(num, den)

  when ::Integer
    ::Kernel.Rational(@num + other * @den, @den)

  when ::Float
    to_f + other

  else
    __coerced__ :+, other
  end
end

#-(other) ⇒ Object



129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'opal/opal/corelib/rational.rb', line 129

def -(other)
  case other
  when ::Rational
    num = @num * other.denominator - @den * other.numerator
    den = @den * other.denominator

    ::Kernel.Rational(num, den)

  when ::Integer
    ::Kernel.Rational(@num - other * @den, @den)

  when ::Float
    to_f - other

  else
    __coerced__ :-, other
  end
end

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



167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'opal/opal/corelib/rational.rb', line 167

def /(other)
  case other
  when ::Rational
    num = @num * other.denominator
    den = @den * other.numerator

    ::Kernel.Rational(num, den)

  when ::Integer
    if other == 0
      to_f / 0.0
    else
      ::Kernel.Rational(@num, @den * other)
    end

  when ::Float
    to_f / other

  else
    __coerced__ :/, other
  end
end

#<=>(other) ⇒ Object



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'opal/opal/corelib/rational.rb', line 94

def <=>(other)
  case other
  when ::Rational
    @num * other.denominator - @den * other.numerator <=> 0

  when ::Integer
    @num - @den * other <=> 0

  when ::Float
    to_f <=> other

  else
    __coerced__ :<=>, other
  end
end

#==(other) ⇒ Object



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'opal/opal/corelib/rational.rb', line 78

def ==(other)
  case other
  when ::Rational
    @num == other.numerator && @den == other.denominator

  when ::Integer
    @num == other && @den == 1

  when ::Float
    to_f == other

  else
    other == self
  end
end

#absObject



226
227
228
# File 'opal/opal/corelib/rational.rb', line 226

def abs
  ::Kernel.Rational(@num.abs, @den.abs)
end

#ceil(precision = 0) ⇒ Object



230
231
232
233
234
235
236
# File 'opal/opal/corelib/rational.rb', line 230

def ceil(precision = 0)
  if precision == 0
    (-(-@num / @den)).ceil
  else
    with_precision(:ceil, precision)
  end
end

#coerce(other) ⇒ Object



65
66
67
68
69
70
71
72
73
74
75
76
# File 'opal/opal/corelib/rational.rb', line 65

def coerce(other)
  case other
  when ::Rational
    [other, self]

  when ::Integer
    [other.to_r, self]

  when ::Float
    [other, to_f]
  end
end

#denominatorObject



61
62
63
# File 'opal/opal/corelib/rational.rb', line 61

def denominator
  @den
end

#floor(precision = 0) ⇒ Object



238
239
240
241
242
243
244
# File 'opal/opal/corelib/rational.rb', line 238

def floor(precision = 0)
  if precision == 0
    (-(-@num / @den)).floor
  else
    with_precision(:floor, precision)
  end
end

#hashObject



246
247
248
# File 'opal/opal/corelib/rational.rb', line 246

def hash
  [::Rational, @num, @den].hash
end

#inspectObject



250
251
252
# File 'opal/opal/corelib/rational.rb', line 250

def inspect
  "(#{self})"
end

#numeratorObject



57
58
59
# File 'opal/opal/corelib/rational.rb', line 57

def numerator
  @num
end

#rationalize(eps = undefined) ⇒ Object



254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
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
# File 'opal/opal/corelib/rational.rb', line 254

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

    if (eps == null) {
      return self;
    }

    var e = #{eps.abs},
        a = #{self - `e`},
        b = #{self + `e`};

    var p0 = 0,
        p1 = 1,
        q0 = 1,
        q1 = 0,
        p2, q2;

    var c, k, t;

    while (true) {
      c = #{`a`.ceil};

      if (#{`c` <= `b`}) {
        break;
      }

      k  = c - 1;
      p2 = k * p1 + p0;
      q2 = k * q1 + q0;
      t  = #{1 / (`b` - `k`)};
      b  = #{1 / (`a` - `k`)};
      a  = t;

      p0 = p1;
      q0 = q1;
      p1 = p2;
      q1 = q2;
    }

    return #{::Kernel.Rational(`c * p1 + p0`, `c * q1 + q0`)};
  }
end

#round(precision = 0) ⇒ Object



300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'opal/opal/corelib/rational.rb', line 300

def round(precision = 0)
  return with_precision(:round, precision) unless precision == 0
  return 0 if @num == 0
  return @num if @den == 1

  num = @num.abs * 2 + @den
  den = @den * 2

  approx = (num / den).truncate

  if @num < 0
    -approx
  else
    approx
  end
end

#to_fObject



317
318
319
# File 'opal/opal/corelib/rational.rb', line 317

def to_f
  @num / @den
end

#to_iObject



321
322
323
# File 'opal/opal/corelib/rational.rb', line 321

def to_i
  truncate
end

#to_rObject



325
326
327
# File 'opal/opal/corelib/rational.rb', line 325

def to_r
  self
end

#to_sObject



329
330
331
# File 'opal/opal/corelib/rational.rb', line 329

def to_s
  "#{@num}/#{@den}"
end

#truncate(precision = 0) ⇒ Object



333
334
335
336
337
338
339
# File 'opal/opal/corelib/rational.rb', line 333

def truncate(precision = 0)
  if precision == 0
    @num < 0 ? ceil : floor
  else
    with_precision(:truncate, precision)
  end
end

#with_precision(method, precision) ⇒ Object



341
342
343
344
345
346
347
348
349
350
351
352
# File 'opal/opal/corelib/rational.rb', line 341

def with_precision(method, precision)
  ::Kernel.raise ::TypeError, 'not an Integer' unless ::Integer === precision

  p = 10**precision
  s = self * p

  if precision < 1
    (s.send(method) / p).to_i
  else
    ::Kernel.Rational(s.send(method), p)
  end
end