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

Add LinearAlgebra.normalize fallback for scalars (#44835) #44925

Merged
merged 5 commits into from
Apr 25, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
20 changes: 16 additions & 4 deletions stdlib/LinearAlgebra/src/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1790,11 +1790,12 @@ end
end

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

Normalize the array `a` so that its `p`-norm equals unity,
i.e. `norm(a, p) == 1`.
See also [`normalize!`](@ref) and [`norm`](@ref).
Normalize `a` so that its `p`-norm equals unity,
i.e. `norm(a, p) == 1`. For scalars, this is similar to sign(a),
except normalize(0) = NaN.
See also [`normalize!`](@ref), [`norm`](@ref), and [`sign`](@ref).

# Examples
```jldoctest
Expand Down Expand Up @@ -1831,6 +1832,14 @@ julia> normalize(a)
0.154303 0.308607 0.617213
0.154303 0.308607 0.617213

julia> normalize(3, 1)
1.0

julia> normalize(-8, 1)
-1.0

julia> normalize(0, 1)
NaN
```
"""
function normalize(a::AbstractArray, p::Real = 2)
Expand All @@ -1843,3 +1852,6 @@ function normalize(a::AbstractArray, p::Real = 2)
return T[]
end
end

normalize(x) = x / norm(x)
normalize(x, p::Real) = x / norm(x, p)
6 changes: 6 additions & 0 deletions stdlib/LinearAlgebra/test/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -375,6 +375,12 @@ end
@test typeof(normalize([1 2 3; 4 5 6])) == Array{Float64,2}
end

@testset "normalize for scalars" begin
@test normalize(8.0) == 1.0
@test normalize(-3.0) == -1.0
stevengj marked this conversation as resolved.
Show resolved Hide resolved
@test isnan(normalize(0.0))
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))
Expand Down