Skip to content

Commit

Permalink
Implement normalize and normalize!
Browse files Browse the repository at this point in the history
Simple helper functions for normalizing vectors

Closes #12047
  • Loading branch information
jiahao committed Oct 20, 2015
1 parent b82ab6a commit 523dcc1
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 0 deletions.
2 changes: 2 additions & 0 deletions base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -676,6 +676,8 @@ export
lufact,
lyap,
norm,
normalize,
normalize!,
nullspace,
ordschur!,
ordschur,
Expand Down
2 changes: 2 additions & 0 deletions base/linalg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ export
lufact!,
lyap,
norm,
normalize,
normalize!,
nullspace,
ordschur!,
ordschur,
Expand Down
47 changes: 47 additions & 0 deletions base/linalg/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -529,3 +529,50 @@ function isapprox{T<:Number,S<:Number}(x::AbstractArray{T}, y::AbstractArray{S};
d = norm(x - y)
return isfinite(d) ? d <= atol + rtol*max(norm(x), norm(y)) : x == y
end

"""
normalize!(v, [p=2])
Normalize the vector `v` in-place with respect to the `p`-norm.
# Inputs
- `v::AbstractVector` - vector to be normalized
- `p::Real` - The `p`-norm to normalize with respect to. Default: 2
# Output
- `v` - A unit vector being the input vector, rescaled to have norm 1. The input vector is modified in-place.
# See also
`normalize`
"""
function normalize!(v::AbstractVector, p::Real=2)
nrm = norm(v, p)
scale!(v, inv(nrm))
end

"""
normalize(v, [p=2])
Normalize the vector `v` with respect to the `p`-norm.
# Inputs
- `v::AbstractVector` - vector to be normalized
- `p::Real` - The `p`-norm to normalize with respect to. Default: 2
# Output
- `v` - A unit vector being a copy of the input vector, scaled to have norm 1
# See also
`normalize!`
"""
function normalize(v::AbstractVector, p::Real=2)
nrm = norm(v, p)
v/nrm
end
9 changes: 9 additions & 0 deletions test/linalg/generic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -150,3 +150,12 @@ let
@test LinAlg.axpy!(α, x, deepcopy(y)) == x .* Matrix{Int}[α]
@test LinAlg.axpy!(α, x, deepcopy(y)) != Matrix{Int}[α] .* x
end

let
v = [3.0, 4.0]
@test norm(v) === 5.0
w = normalize(v)
@test w == [0.6000000000000001,0.8]
@test norm(w) === 1.0
@test normalize!(v) == w
end

0 comments on commit 523dcc1

Please sign in to comment.