Skip to content

Commit

Permalink
Merge pull request JuliaLang#12935 from stevengj/generic_vecnorm_test
Browse files Browse the repository at this point in the history
fixed bug and added test for generic vecnorm of array of arrays
  • Loading branch information
andreasnoack committed Sep 4, 2015
2 parents cd87abb + 95f3015 commit a4a321a
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
15 changes: 10 additions & 5 deletions base/linalg/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -107,24 +107,29 @@ function generic_vecnorm1(x)
return convert(T, sum)
end

# faster computation of norm(x)^2, avoiding overflow for integers
norm_sqr(x) = norm(x)^2
norm_sqr(x::Number) = abs2(x)
norm_sqr{T<:Integer}(x::Union{T,Complex{T},Rational{T}}) = abs2(float(x))

function generic_vecnorm2(x)
maxabs = vecnormInf(x)
(maxabs == 0 || isinf(maxabs)) && return maxabs
s = start(x)
(v, s) = next(x, s)
T = typeof(maxabs)
if isfinite(length(x)*maxabs*maxabs) && maxabs*maxabs != 0 # Scaling not necessary
sum::promote_type(Float64, T) = abs2(norm(v)/norm(one(v)))
sum::promote_type(Float64, T) = norm_sqr(v)
while !done(x, s)
(v, s) = next(x, s)
sum += abs2(norm(v)/norm(one(v)))
sum += norm_sqr(v)
end
return convert(T, sqrt(sum))
else
sum = abs2(norm(v)/maxabs)
while !done(x, s)
(v, s) = next(x, s)
sum += abs2(norm(v)/maxabs)
sum += (norm(v)/maxabs)^2
end
return convert(T, maxabs*sqrt(sum))
end
Expand All @@ -144,10 +149,10 @@ function generic_vecnormp(x, p)
end
spp::promote_type(Float64, T) = p
if -1 <= p <= 1 || (isfinite(length(x)*maxabs^spp) && maxabs^spp != 0) # scaling not necessary
sum::promote_type(Float64, T) = (norm(v)/norm(one(v)))^spp
sum::promote_type(Float64, T) = norm(v)^spp
while !done(x, s)
(v, s) = next(x, s)
sum += (norm(v)/norm(one(v)))^spp
sum += norm(v)^spp
end
return convert(T, sum^inv(spp))
else # rescaling
Expand Down
7 changes: 7 additions & 0 deletions test/linalg/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -124,3 +124,10 @@ end

@test norm([2.4e-322, 4.4e-323]) 2.47e-322
@test norm([2.4e-322, 4.4e-323], 3) 2.4e-322

# test generic vecnorm for arrays of arrays
let x = Vector{Int}[[1,2], [3,4]]
@test norm(x) sqrt(30)
@test norm(x, 1) sqrt(5) + 5
@test norm(x, 3) cbrt(sqrt(125)+125)
end

0 comments on commit a4a321a

Please sign in to comment.