Skip to content
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

Fix vecnorm for Vector{Vector{T}} #22945

Merged
merged 1 commit into from
Aug 7, 2017
Merged
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
5 changes: 2 additions & 3 deletions base/linalg/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -431,16 +431,15 @@ julia> vecnorm([1 2 3 4 5 6 7 8 9])
```
"""
function vecnorm(itr, p::Real=2)
isempty(itr) && return float(real(zero(eltype(itr))))
isempty(itr) && return float(norm(zero(eltype(itr))))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Seems like it would be clearer to to use a return-type declaration? Then we could just return 0 in the empty case and return count(...) in the p == 0 case.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Notice that the two type computations for the empty case and the p=0 case are slightly different. The empty case uses zero(Type) whereas the p=0 case avoids zero(Type) which allows us to compute

julia> norm(Float64[])
0.0

as well as

julia> norm([[1,2], [3,4]], 0)
2.0

I think we'd have to give up on one of them if we want to use return type annotation instead.

if p == 2
return vecnorm2(itr)
elseif p == 1
return vecnorm1(itr)
elseif p == Inf
return vecnormInf(itr)
elseif p == 0
return convert(typeof(float(real(zero(eltype(itr))))),
countnz(itr))
return typeof(float(norm(first(itr))))(count(!iszero, itr))
elseif p == -Inf
return vecnormMinusInf(itr)
else
Expand Down
2 changes: 1 addition & 1 deletion test/arrayops.jl
Original file line number Diff line number Diff line change
Expand Up @@ -457,8 +457,8 @@ end
# @test find(s) == [1,2,3,4,5]
@test find(c -> c == 'l', s) == [3]
g = graphemes("日本語")
@test find(g) == [1,2,3]
@test find(isascii, g) == Int[]
@test find((i % 2 for i in 1:10)) == collect(1:2:9)
end
@testset "findn" begin
b = findn(ones(2,2,2,2))
Expand Down
3 changes: 2 additions & 1 deletion test/linalg/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -270,7 +270,8 @@ end

@testset "generic vecnorm for arrays of arrays" begin
x = Vector{Int}[[1,2], [3,4]]
@test norm(x) ≈ sqrt(30)
@test @inferred(norm(x)) ≈ sqrt(30)
@test norm(x, 0) == length(x)
@test norm(x, 1) ≈ sqrt(5) + 5
@test norm(x, 3) ≈ cbrt(sqrt(125)+125)
end
Expand Down