class Matrc::Fraction

Attributes

den[RW]
num[RW]

Public Class Methods

new(num, den) click to toggle source
# File lib/matrc/fraction.rb, line 9
def initialize(num, den)
  
  com = gcd(num, den)
  if (den < 0)
    @num, @den = ((-1*num)/com), ((-1*den)/com)
  else
    @num, @den = num/com, den/com
  end
end

Public Instance Methods

%(other) click to toggle source
# File lib/matrc/fraction.rb, line 55
def %(other)
  if !(other.is_a? Fraction)
        other = Fraction.new(other,1)
end
  a = (@num*other.den)
  b = (@den * other.num)
  c = a%b
  c
end
*(other) click to toggle source
# File lib/matrc/fraction.rb, line 41
def *(other)
  if !(other.is_a? Fraction)
        other = Fraction.new(other,1)
   end
   Fraction.new(@num * other.num, @den *other.den)
end
+(other) click to toggle source
# File lib/matrc/fraction.rb, line 27
def +(other)
  if !(other.is_a? Fraction)
       other = Fraction.new(other,1)
end
       Fraction.new(@num* other.den + other.num*@den, @den * other.den)
end
-(other) click to toggle source
# File lib/matrc/fraction.rb, line 34
def -(other)
  if !(other.is_a? Fraction)
        other = Fraction.new(other,1)
end
  Fraction.new(@num* other.den - other.num*@den, @den * other.den)
end
-@() click to toggle source
# File lib/matrc/fraction.rb, line 69
def -@()
  Fraction.new(@num * -1, @den)
end
/(other) click to toggle source
# File lib/matrc/fraction.rb, line 48
def /(other)
  if !(other.is_a? Fraction)
        other = Fraction.new(other,1)
end
  Fraction.new(@num * other.den, @den *other.num)
end
<=>(other) click to toggle source
# File lib/matrc/fraction.rb, line 77
def <=>(other)
 if !(other.is_a? Fraction)
         other = Fraction.new(other,1)
 end
 self.to_float() <=> other.to_float()
end
abs() click to toggle source
# File lib/matrc/fraction.rb, line 65
def abs()
   Fraction.new(@num.abs, @den.abs)
end
coerce(other) click to toggle source
# File lib/matrc/fraction.rb, line 84
def coerce(other)
     [self,Fraction.new(other,1)]
end
gcd(u, v) click to toggle source
# File lib/matrc/fraction.rb, line 89
def gcd(u, v)
        u, v = u.abs, v.abs
        while v != 0
                u, v = v, u % v
        end
        u
end
reciprocal() click to toggle source
# File lib/matrc/fraction.rb, line 73
def reciprocal()
  Fraction.new(@den, @num)
end
to_float() click to toggle source
# File lib/matrc/fraction.rb, line 23
def to_float()
  (@num.to_f/@den.to_f)    
end
to_string() click to toggle source
# File lib/matrc/fraction.rb, line 19
def to_string()
  "#{@num}/#{@den}"
end