Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix inf rational #39063

Merged
merged 2 commits into from
Jan 4, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion base/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -278,13 +278,35 @@ function -(x::Rational{T}) where T<:Unsigned
x
end

for (op,chop) in ((:+,:checked_add), (:-,:checked_sub), (:rem,:rem), (:mod,:mod))
function +(x::Rational, y::Rational)
xp, yp = promote(x, y)
if isinf(x) && x == y
return xp
end
xd, yd = divgcd(promote(x.den, y.den)...)
Rational(checked_add(checked_mul(x.num,yd), checked_mul(y.num,xd)), checked_mul(x.den,yd))
end

function -(x::Rational, y::Rational)
xp, yp = promote(x, y)
if isinf(x) && x == -y
return xp
end
xd, yd = divgcd(promote(x.den, y.den)...)
Rational(checked_sub(checked_mul(x.num,yd), checked_mul(y.num,xd)), checked_mul(x.den,yd))
end

for (op,chop) in ((:rem,:rem), (:mod,:mod))
@eval begin
function ($op)(x::Rational, y::Rational)
xd, yd = divgcd(promote(x.den, y.den)...)
Rational(($chop)(checked_mul(x.num,yd), checked_mul(y.num,xd)), checked_mul(x.den,yd))
end
end
end

for (op,chop) in ((:+,:checked_add), (:-,:checked_sub), (:rem,:rem), (:mod,:mod))
@eval begin
function ($op)(x::Rational, y::Integer)
unsafe_rational(($chop)(x.num, checked_mul(x.den, y)), x.den)
end
Expand Down
8 changes: 8 additions & 0 deletions test/rational.jl
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,14 @@ using Test
@test abs(one(Rational{UInt})) === one(Rational{UInt})
@test abs(one(Rational{Int})) === one(Rational{Int})
@test abs(-one(Rational{Int})) === one(Rational{Int})

# inf addition
@test 1//0 + 1//0 == 1//0
@test -1//0 - 1//0 == -1//0
@test_throws DivideError 1//0 - 1//0
@test_throws DivideError -1//0 + 1//0
@test Int128(1)//0 + 1//0 isa Rational{Int128}
@test 1//0 + Int128(1)//0 isa Rational{Int128}
end

@testset "Rational methods" begin
Expand Down