From 075affb15a0513c601ad85ce471ce6bb5cef8286 Mon Sep 17 00:00:00 2001 From: Andreas Noack Date: Thu, 24 Jan 2019 20:18:53 +0100 Subject: [PATCH] Fix zero norm of number (#30809) Fixes #30631 --- stdlib/LinearAlgebra/src/generic.jl | 16 +++++++++++++++- stdlib/LinearAlgebra/test/generic.jl | 4 ++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/stdlib/LinearAlgebra/src/generic.jl b/stdlib/LinearAlgebra/src/generic.jl index ca747db604fc8..31a02a40e8a24 100644 --- a/stdlib/LinearAlgebra/src/generic.jl +++ b/stdlib/LinearAlgebra/src/generic.jl @@ -466,7 +466,21 @@ julia> norm(-2, Inf) 2 ``` """ -@inline norm(x::Number, p::Real=2) = p == 0 ? (x==0 ? zero(abs(x)) : oneunit(abs(x))) : abs(x) +@inline function norm(x::Number, p::Real=2) + afx = abs(float(x)) + if p == 0 + if x == 0 + return zero(afx) + elseif !isnan(x) + return oneunit(afx) + else + return afx + end + else + return afx + end +end + norm(::Missing, p::Real=2) = missing # special cases of opnorm diff --git a/stdlib/LinearAlgebra/test/generic.jl b/stdlib/LinearAlgebra/test/generic.jl index 13d18e1d29b23..e4b7cfaa49057 100644 --- a/stdlib/LinearAlgebra/test/generic.jl +++ b/stdlib/LinearAlgebra/test/generic.jl @@ -186,11 +186,15 @@ end @test issymmetric(a) @test ishermitian(one(elty)) @test det(a) == a + @test norm(a) == abs(a) + @test norm(a, 0) == 1 end @test !issymmetric(NaN16) @test !issymmetric(NaN32) @test !issymmetric(NaN) + @test norm(NaN) === NaN + @test norm(NaN, 0) === NaN end @test rank(fill(0, 0, 0)) == 0