Skip to content

Commit e4b29f7

Browse files
authored
Fix some corner cases of isapprox with unsigned integers (#55828)
1 parent 7a76e32 commit e4b29f7

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

base/floatfuncs.jl

+3-1
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,9 @@ 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+
# We need to take the difference `max` - `min` when comparing unsigned integers.
236+
_x, _y = x < y ? (x, y) : (y, x)
237+
return norm(_y - _x) <= max(atol, rtol*max(norm(_x), norm(_y)))
236238
end
237239
end
238240

test/floatfuncs.jl

+29
Original file line numberDiff line numberDiff line change
@@ -257,6 +257,35 @@ end
257257
end
258258
end
259259

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

0 commit comments

Comments
 (0)