Class: Rational

Inherits:
Object show all
Defined in:
lib/kaki/utils/rec_decimal.rb

Instance Method Summary collapse

Instance Method Details

#to_rec_decimalString

分数を循環小数に直す

Returns:


4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/kaki/utils/rec_decimal.rb', line 4

def to_rec_decimal
  f, num = (self < 0) ? ["-", -self] : ["", self]
  
  i = num.to_i
  result = f + i.to_s
  ra = num - i
  return result if ra.zero?
  result += "."
  
  remainder = ra.numerator
  deno      = ra.denominator
  place = []
  rems = []
  begin
    rems  << remainder
    place << remainder * 10 / deno
    remainder = remainder * 10 % deno
    return result + place.join if remainder.zero?
  end while not (idx = rems.find_index(remainder))
  place.insert(idx, "(")
  result + place.join + ")"
end