class Rational

if ENV

$LOAD_PATH.unshift ENV["RUBY_RAT"]
require "rational.rb"

elsif ENV

require "frac"
class Fraction < Numeric
  instance_eval do
    alias new! new
  end

  def initialize(n, d = 1)
    @numerator, @denominator = n, d
  end
end

Rational = Fraction
alias Rational frac

class Rational < Numeric
  def self.unity; new(1,1); end
  def self.zero; new(0,1); end
  def inverse; 1 / self; end
end

else

require "rational"

end

Public Class Methods

ground() click to toggle source
# File lib/algebra/rational.rb, line 34
def self.ground; Integer; end
regulate(o) click to toggle source
# File lib/algebra/rational.rb, line 36
def self.regulate(o)
  case o
  when self
    o
  when Numeric
    Rational(o)
  else
    nil
  end
end
unity() click to toggle source

def self.unity; new(1, 1); end def self.zero; new(0, 1); end

# File lib/algebra/rational.rb, line 69
def self.unity; Rational(1); end
wedge(otype) click to toggle source
# File lib/algebra/rational.rb, line 47
def self.wedge(otype)
  if otype <= Integer || otype <= self
    self
  else
    otype
  end
end
zero() click to toggle source
# File lib/algebra/rational.rb, line 70
def self.zero; Rational(0); end

Public Instance Methods

devide?(other) click to toggle source
# File lib/algebra/rational.rb, line 55
def devide?(other); true; end
gcd_coeff(b) click to toggle source
# File lib/algebra/rational.rb, line 57
def gcd_coeff(b)
  if b.zero?
    [self, self.class.unity, self.class.zero]
  else
    q, r = divmod b
    d, x, y = b.gcd_coeff(r)
    [d, y, x - y * q]
  end
end
inspect() click to toggle source
# File lib/algebra/gaussian-elimination.rb, line 332
def inspect; to_s; end
mod(o) click to toggle source
# File lib/algebra/rational.rb, line 73
def mod(o)
  raise ZeroDivisionError, "devided by 0" if o.zero?
  den, a, = denominator.gcd_coeff(o)
  num = (numerator * a) % o
  q, r = num.divmod den
  raise "denominator(#{denominator}) can not divide numerator(#{numerator}) mod #{o}" unless r.zero?
  q
end