Skip to content

Commit 35a4427

Browse files
authored
Iterator norm in isapprox for Arrays (#1378)
1 parent 98723df commit 35a4427

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

src/generic.jl

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2004,7 +2004,7 @@ function isapprox(x::AbstractArray, y::AbstractArray;
20042004
atol::Real=0,
20052005
rtol::Real=Base.rtoldefault(promote_leaf_eltypes(x),promote_leaf_eltypes(y),atol),
20062006
nans::Bool=false, norm::Function=norm)
2007-
d = norm(x - y)
2007+
d = norm_x_minus_y(x, y)
20082008
if isfinite(d)
20092009
return iszero(rtol) ? d <= atol : d <= max(atol, rtol*max(norm(x), norm(y)))
20102010
else
@@ -2014,6 +2014,18 @@ function isapprox(x::AbstractArray, y::AbstractArray;
20142014
end
20152015
end
20162016

2017+
norm_x_minus_y(x, y) = norm(x - y)
2018+
FastContiguousArrayView{T,N,P<:Array,I<:Tuple{AbstractUnitRange, Vararg{Any}}} = Base.SubArray{T,N,P,I,true}
2019+
const ArrayOrFastContiguousArrayView = Union{Array, FastContiguousArrayView}
2020+
function norm_x_minus_y(x::ArrayOrFastContiguousArrayView, y::ArrayOrFastContiguousArrayView)
2021+
Base.promote_shape(size(x), size(y)) # ensure compatible size
2022+
if isempty(x) && isempty(y)
2023+
norm(zero(eltype(x)) - zero(eltype(y)))
2024+
else
2025+
norm(Iterators.map(splat(-), zip(x,y)))
2026+
end
2027+
end
2028+
20172029
"""
20182030
normalize!(a::AbstractArray, p::Real=2)
20192031

test/generic.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -943,4 +943,11 @@ end
943943
@test B == A2
944944
end
945945

946+
@testset "isapprox for Arrays" begin
947+
A = rand(3,3)
948+
n = @allocated isapprox(A, A)
949+
@test n == 0
950+
@test Int[] Int[]
951+
end
952+
946953
end # module TestGeneric

0 commit comments

Comments
 (0)