Last active
August 29, 2015 14:16
-
-
Save tkuro11/5c96e0a94d822bf2f806 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Float | |
def decimal | |
self % 1.0 # extract decimal part | |
end | |
end | |
module Enumerable | |
def scan c,&block | |
s = [c] | |
self.each {|v| | |
s << (c = block.call(v,c)) | |
} | |
s | |
end | |
end | |
class ContFraction < Array | |
def initialize(t=0.0, eps = 0.0001) | |
if t.class == Float then | |
push t.to_i | |
while t.decimal.abs > eps | |
t = 1.0/t.decimal | |
push t.to_i | |
end | |
else | |
super(t) | |
end | |
end | |
def indent lines | |
@len = lines.map(&:length) | |
p = @len.scan(0) {|i,curpos| curpos + (i + 3)} | |
p[p.length-1] -= 4 | |
@pos = p.clone | |
lines.each {|line| line.prepend " "*p.shift} | |
lines | |
end | |
def decorate lines | |
lftmst = @pos.pop - 3 | |
(lines.length-2).downto(0){ |i| | |
l = lftmst - @pos[i] +1 - @len[i] | |
lines[i] += " + " + "-" * l | |
lines.insert(i, " " * (@len[i]+@pos[i]+3) + "1".center(l)) | |
} | |
lines | |
end | |
def inspect | |
lines = self.map(&:to_s) | |
lines = indent lines | |
lines = decorate lines | |
lines.join "\n" | |
end | |
def to_r | |
seq = self.to_a | |
ans = Rational(seq.pop) | |
while not seq.empty? | |
ans = seq.pop + 1/ans | |
end | |
ans | |
end | |
end | |
if $0 == __FILE__ then | |
t = ContFraction.new ARGV.pop.to_f | |
p t | |
puts "a = #{t.to_r}" | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment