summaryrefslogtreecommitdiff
path: root/lib/rational.rb
diff options
context:
space:
mode:
Diffstat (limited to 'lib/rational.rb')
-rw-r--r--lib/rational.rb75
1 files changed, 53 insertions, 22 deletions
diff --git a/lib/rational.rb b/lib/rational.rb
index 1adac61e83..59588528ab 100644
--- a/lib/rational.rb
+++ b/lib/rational.rb
@@ -238,6 +238,10 @@ class Rational < Numeric
end
end
+ def div(other)
+ (self / other).floor
+ end
+
#
# Returns the remainder when this value is divided by +other+.
#
@@ -249,7 +253,7 @@ class Rational < Numeric
# r % 0.26 # -> 0.19
#
def % (other)
- value = (self / other).to_i
+ value = (self / other).floor
return self - other * value
end
@@ -261,7 +265,7 @@ class Rational < Numeric
# r.divmod Rational(1,2) # -> [3, Rational(1,4)]
#
def divmod(other)
- value = (self / other).to_i
+ value = (self / other).floor
return value, self - other * value
end
@@ -270,7 +274,7 @@ class Rational < Numeric
#
def abs
if @numerator > 0
- Rational.new!(@numerator, @denominator)
+ self
else
Rational.new!(-@numerator, @denominator)
end
@@ -345,8 +349,35 @@ class Rational < Numeric
# Rational(-7,4) == -1.75 # -> true
# Rational(-7,4).to_i == (-1.75).to_i # false
#
- def to_i
- Integer(@numerator.div(@denominator))
+
+ def floor()
+ @numerator.div(@denominator)
+ end
+
+ def ceil()
+ -((-@numerator).div(@denominator))
+ end
+
+ def truncate()
+ if @numerator < 0
+ return -((-@numerator).div(@denominator))
+ end
+ @numerator.div(@denominator)
+ end
+
+ alias_method :to_i, :truncate
+
+ def round()
+ if @numerator < 0
+ num = -@numerator
+ num = num * 2 + @denominator
+ den = @denominator * 2
+ -(num.div(den))
+ else
+ num = @numerator * 2 + @denominator
+ den = @denominator * 2
+ num.div(den)
+ end
end
#
@@ -476,10 +507,11 @@ end
class Fixnum
alias quof quo
- undef quo
- # If Rational is defined, returns a Rational number instead of a Fixnum.
+ remove_method :quo
+
+ # If Rational is defined, returns a Rational number instead of a Float.
def quo(other)
- Rational.new!(self,1) / other
+ Rational.new!(self, 1) / other
end
alias rdiv quo
@@ -488,26 +520,18 @@ class Fixnum
if other >= 0
self.power!(other)
else
- Rational.new!(self,1)**other
+ Rational.new!(self, 1)**other
end
end
-
- unless defined? 1.power!
- alias power! **
- alias ** rpower
- end
end
class Bignum
- unless defined? Complex
- alias power! **
- end
-
alias quof quo
- undef quo
- # If Rational is defined, returns a Rational number instead of a Bignum.
+ remove_method :quo
+
+ # If Rational is defined, returns a Rational number instead of a Float.
def quo(other)
- Rational.new!(self,1) / other
+ Rational.new!(self, 1) / other
end
alias rdiv quo
@@ -519,8 +543,15 @@ class Bignum
Rational.new!(self, 1)**other
end
end
+end
- unless defined? Complex
+unless defined? 1.power!
+ class Fixnum
+ alias power! **
+ alias ** rpower
+ end
+ class Bignum
+ alias power! **
alias ** rpower
end
end