class Stellar::Util::ContinuedFraction
Constants
- MAX_PRECISION
Attributes
f[R]
i[R]
Public Class Methods
best_r(number, max_precision=MAX_PRECISION)
click to toggle source
# File lib/stellar/util/continued_fraction.rb, line 8 def self.best_r(number, max_precision=MAX_PRECISION) cur_cf = new(number) loop do next_cf = cur_cf.extend() cur_r = cur_cf.to_r(max_precision) next_r = next_cf.to_r(max_precision) break cur_r if cur_cf.done? || cur_r == next_r cur_cf = next_cf end cur_cf.to_r(max_precision) end
new(val, parents=[])
click to toggle source
# File lib/stellar/util/continued_fraction.rb, line 24 def initialize(val, parents=[]) @i = val.floor @f = val - @i @parents = parents end
Public Instance Methods
convergents()
click to toggle source
# File lib/stellar/util/continued_fraction.rb, line 43 def convergents return @convergents if defined? @convergents c = [Fraction.new(0,1), Fraction.new(1,0)] to_a.each_with_index do |a, i| i = i + 2 h = a * c[i-1].n + c[i-2].n k = a * c[i-1].d + c[i-2].d c << Fraction.new(h,k) end @converegents = c[2..-1] end
done?()
click to toggle source
# File lib/stellar/util/continued_fraction.rb, line 66 def done? @f == 0 end
error(actual)
click to toggle source
# File lib/stellar/util/continued_fraction.rb, line 34 def error(actual) (actual - to_f).abs end
extend(count=1)
click to toggle source
# File lib/stellar/util/continued_fraction.rb, line 70 def extend(count=1) result = self count.times do break if result.done? result = ContinuedFraction.new(1 / result.f, result.to_a) end result end
to_a()
click to toggle source
# File lib/stellar/util/continued_fraction.rb, line 30 def to_a @parents + [i] end
to_f()
click to toggle source
# File lib/stellar/util/continued_fraction.rb, line 38 def to_f convergent = convergents.last convergent.n / convergent.d.to_f end
to_r(max_precision=MAX_PRECISION)
click to toggle source
# File lib/stellar/util/continued_fraction.rb, line 58 def to_r(max_precision=MAX_PRECISION) fraction = convergents.take_while do |c| c.n <= max_precision && c.d <= max_precision end.last Rational(fraction.n, fraction.d) end