Skip to content

Commit 409808e

Browse files
committed
Fix some corner cases of isapprox with unsigned integers
1 parent bce8f04 commit 409808e

File tree

2 files changed

+24
-1
lines changed

2 files changed

+24
-1
lines changed

base/floatfuncs.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,8 @@ function isapprox(x::Integer, y::Integer;
232232
if norm === abs && atol < 1 && rtol == 0
233233
return x == y
234234
else
235-
return norm(x - y) <= max(atol, rtol*max(norm(x), norm(y)))
235+
_x, _y = x < y ? (x, y) : (y, x)
236+
return norm(_y - _x) <= max(atol, rtol*max(norm(_x), norm(_y)))
236237
end
237238
end
238239

test/floatfuncs.jl

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,28 @@ end
257257
end
258258
end
259259

260+
@testset "isapprox and unsigned integers" begin
261+
for T in Base.BitUnsigned_types
262+
# The order of the operands for difference between unsigned integers is
263+
# very important, test both combinations.
264+
@test isapprox(T(42), T(42); rtol=T(0), atol=0.5)
265+
@test !isapprox(T(0), T(1); rtol=T(0), atol=0.5)
266+
@test !isapprox(T(1), T(0); rtol=T(0), atol=0.5)
267+
@test isapprox(T(1), T(3); atol=T(2))
268+
@test isapprox(T(4), T(2); atol=T(2))
269+
@test isapprox(T(5), T(7); atol=typemax(T))
270+
@test isapprox(T(8), T(6); atol=typemax(T))
271+
@test isapprox(T(1), T(2); rtol=1)
272+
@test isapprox(T(6), T(3); rtol=1)
273+
@test !isapprox(typemin(T), typemax(T))
274+
@test !isapprox(typemax(T), typemin(T))
275+
@test !isapprox(typemin(T), typemax(T); atol=typemax(T)-T(1))
276+
@test !isapprox(typemax(T), typemin(T); atol=typemax(T)-T(1))
277+
@test isapprox(typemin(T), typemax(T); atol=typemax(T))
278+
@test isapprox(typemax(T), typemin(T); atol=typemax(T))
279+
end
280+
end
281+
260282
@testset "Conversion from floating point to unsigned integer near extremes (#51063)" begin
261283
@test_throws InexactError UInt32(4.2949673f9)
262284
@test_throws InexactError UInt64(1.8446744f19)

0 commit comments

Comments
 (0)