Skip to content

Commit 1a333a9

Browse files
authored
fix inf rational (#39063)
1 parent ee66728 commit 1a333a9

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

base/rational.jl

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -278,13 +278,35 @@ function -(x::Rational{T}) where T<:Unsigned
278278
x
279279
end
280280

281-
for (op,chop) in ((:+,:checked_add), (:-,:checked_sub), (:rem,:rem), (:mod,:mod))
281+
function +(x::Rational, y::Rational)
282+
xp, yp = promote(x, y)
283+
if isinf(x) && x == y
284+
return xp
285+
end
286+
xd, yd = divgcd(promote(x.den, y.den)...)
287+
Rational(checked_add(checked_mul(x.num,yd), checked_mul(y.num,xd)), checked_mul(x.den,yd))
288+
end
289+
290+
function -(x::Rational, y::Rational)
291+
xp, yp = promote(x, y)
292+
if isinf(x) && x == -y
293+
return xp
294+
end
295+
xd, yd = divgcd(promote(x.den, y.den)...)
296+
Rational(checked_sub(checked_mul(x.num,yd), checked_mul(y.num,xd)), checked_mul(x.den,yd))
297+
end
298+
299+
for (op,chop) in ((:rem,:rem), (:mod,:mod))
282300
@eval begin
283301
function ($op)(x::Rational, y::Rational)
284302
xd, yd = divgcd(promote(x.den, y.den)...)
285303
Rational(($chop)(checked_mul(x.num,yd), checked_mul(y.num,xd)), checked_mul(x.den,yd))
286304
end
305+
end
306+
end
287307

308+
for (op,chop) in ((:+,:checked_add), (:-,:checked_sub), (:rem,:rem), (:mod,:mod))
309+
@eval begin
288310
function ($op)(x::Rational, y::Integer)
289311
unsafe_rational(($chop)(x.num, checked_mul(x.den, y)), x.den)
290312
end

test/rational.jl

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,14 @@ using Test
116116
@test abs(one(Rational{UInt})) === one(Rational{UInt})
117117
@test abs(one(Rational{Int})) === one(Rational{Int})
118118
@test abs(-one(Rational{Int})) === one(Rational{Int})
119+
120+
# inf addition
121+
@test 1//0 + 1//0 == 1//0
122+
@test -1//0 - 1//0 == -1//0
123+
@test_throws DivideError 1//0 - 1//0
124+
@test_throws DivideError -1//0 + 1//0
125+
@test Int128(1)//0 + 1//0 isa Rational{Int128}
126+
@test 1//0 + Int128(1)//0 isa Rational{Int128}
119127
end
120128

121129
@testset "Rational methods" begin

0 commit comments

Comments
 (0)