Skip to content

Commit

Permalink
Fixed norm (#30481)
Browse files Browse the repository at this point in the history
* Fixed norm

* Modified and added tests for norm

* Added AbstractFloat for Quaternion Type

* Updated norm

* Modified norm(::Number) to return float

* Removed -p test for norm

* Updated tests

* Minor change in tests
  • Loading branch information
raghav9-97 authored and andreasnoack committed Jan 7, 2019
1 parent 49b8e91 commit 40cdae2
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 7 deletions.
14 changes: 7 additions & 7 deletions stdlib/LinearAlgebra/src/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -469,25 +469,25 @@ For numbers, return ``\\left( |x|^p \\right)^{1/p}``.
# Examples
```jldoctest
julia> norm(2, 1)
2
2.0
julia> norm(-2, 1)
2
2.0
julia> norm(2, 2)
2
2.0
julia> norm(-2, 2)
2
2.0
julia> norm(2, Inf)
2
2.0
julia> norm(-2, Inf)
2
2.0
```
"""
@inline norm(x::Number, p::Real=2) = p == 0 ? (x==0 ? zero(abs(x)) : oneunit(abs(x))) : abs(x)
@inline norm(x::Number, p::Real=2) = p == 0 ? (x==0 ? zero(abs(float(x))) : oneunit(abs(float(x)))) : abs(float(x))
norm(::Missing, p::Real=2) = missing

# special cases of opnorm
Expand Down
5 changes: 5 additions & 0 deletions stdlib/LinearAlgebra/test/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,11 @@ end
end
end

@testset "Issue #30466" begin
@test norm([typemin(Int), typemin(Int)], Inf) == -float(typemin(Int))
@test norm([typemin(Int), typemin(Int)], 1) == -2float(typemin(Int))
end

@testset "potential overflow in normalize!" begin
δ = inv(prevfloat(typemax(Float64)))
v = [δ, -δ]
Expand Down
1 change: 1 addition & 0 deletions test/testhelpers/Quaternions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ struct Quaternion{T<:Real} <: Number
end
Quaternion(s::Real, v1::Real, v2::Real, v3::Real) = Quaternion(promote(s, v1, v2, v3)...)
Base.abs2(q::Quaternion) = q.s*q.s + q.v1*q.v1 + q.v2*q.v2 + q.v3*q.v3
Base.float(z::Quaternion{T}) where T = Quaternion(float(z.s), float(z.v1), float(z.v2), float(z.v3))
Base.abs(q::Quaternion) = sqrt(abs2(q))
Base.real(::Type{Quaternion{T}}) where {T} = T
Base.conj(q::Quaternion) = Quaternion(q.s, -q.v1, -q.v2, -q.v3)
Expand Down

0 comments on commit 40cdae2

Please sign in to comment.