Skip to content

Commit

Permalink
Merge pull request #3382 from GunnarFarneback/rational
Browse files Browse the repository at this point in the history
Avoid some rational overflow
  • Loading branch information
StefanKarpinski committed Jun 13, 2013
2 parents c33094a + bec6fc5 commit 23ee2ea
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 9 deletions.
2 changes: 1 addition & 1 deletion base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ function gcd{T<:Integer}(a::T, b::T)
g = abs(a)
neg ? -g : g
end
lcm{T<:Integer}(a::T, b::T) = div(a*b, gcd(b,a))
lcm{T<:Integer}(a::T, b::T) = a * div(b, gcd(b,a))

gcd(a::Integer) = a
lcm(a::Integer) = a
Expand Down
16 changes: 8 additions & 8 deletions base/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -123,8 +123,14 @@ hash(x::Rational) = isinteger(x) ? hash(x.num) :
bitmix(hash(x.num), hash(x.den))

-(x::Rational) = (-x.num) // x.den
+(x::Rational, y::Rational) = (x.num*y.den + x.den*y.num) // (x.den*y.den)
-(x::Rational, y::Rational) = (x.num*y.den - x.den*y.num) // (x.den*y.den)
for op in (:+, :-, :rem, :mod)
@eval begin
function ($op)(x::Rational, y::Rational)
g = gcd(x.den, y.den)
Rational(($op)(x.num * div(y.den, g), y.num * div(x.den, g)), x.den * div(y.den, g))
end
end
end
*(x::Rational, y::Rational) = (x.num*y.num) // (x.den*y.den)
/(x::Rational, y::Rational) = (x.num*y.den) // (x.den*y.num)
/(x::Rational, z::Complex ) = inv(z/x)
Expand All @@ -149,12 +155,6 @@ hash(x::Rational) = isinteger(x) ? hash(x.num) :
<=(x::Rational, y::Real ) = x.num <= x.den*y
<=(x::Real , y::Rational) = x*y.den <= y.num

rem(x::Rational, y::Rational) = Rational(rem(x.num*y.den, x.den*y.num),
x.den*y.den)

mod(x::Rational, y::Rational) = Rational(mod(x.num*y.den, x.den*y.num),
x.den*y.den)

div(x::Rational, y::Rational) = div(x.num*y.den, x.den*y.num)
div(x::Rational, y::Real ) = div(x.num, x.den*y)
div(x::Real , y::Rational) = div(x*y.den, y.num)
Expand Down

0 comments on commit 23ee2ea

Please sign in to comment.