Skip to content

Iterator norm in isapprox for Arrays #1378

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

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
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
14 changes: 13 additions & 1 deletion src/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2004,7 +2004,12 @@ function isapprox(x::AbstractArray, y::AbstractArray;
atol::Real=0,
rtol::Real=Base.rtoldefault(promote_leaf_eltypes(x),promote_leaf_eltypes(y),atol),
nans::Bool=false, norm::Function=norm)
d = norm(x - y)
Base.promote_shape(size(x), size(y)) # ensure compatible size
d = if isempty(x) && isempty(y)
norm(zero(eltype(x)) - zero(eltype(y)))
else
norm_x_minus_y(x, y)
end
if isfinite(d)
return iszero(rtol) ? d <= atol : d <= max(atol, rtol*max(norm(x), norm(y)))
else
Expand All @@ -2014,6 +2019,13 @@ function isapprox(x::AbstractArray, y::AbstractArray;
end
end

norm_x_minus_y(x, y) = norm(x - y)
FastContiguousArrayView{T,N,P<:Array,I<:Tuple{AbstractUnitRange, Vararg{Any}}} = Base.SubArray{T,N,P,I,true}
const ArrayOrFastContiguousArrayView = Union{Array, FastContiguousArrayView}
function norm_x_minus_y(x::ArrayOrFastContiguousArrayView, y::ArrayOrFastContiguousArrayView)
norm(Iterators.map(splat(-), zip(x,y)))
end

"""
normalize!(a::AbstractArray, p::Real=2)

Expand Down
7 changes: 7 additions & 0 deletions test/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -938,4 +938,11 @@ end
@test B == A2
end

@testset "isapprox for Arrays" begin
A = rand(3,3)
n = @allocated isapprox(A, A)
@test n == 0
@test Int[] ≈ Int[]
end

end # module TestGeneric