Skip to content

Commit

Permalink
Change eigvals(::Number) to return a scalar (JuliaLang#27730)
Browse files Browse the repository at this point in the history
This is a proposal for how eigvals could return a scalar when given a
scalar input, in line with what svdvals does. (See issue #27687)

Promotion to float is also skipped. (Just like svdvals, eigvals will now
return an integer for scalar real integer input.) For complex scalar
input, the return type will depend on whether the imaginary component is
zero, as before.

Since Julia allows indexing into, and iterating over, a scalar as if it
were a length-1 vector, this change should have minimal effect on
existing code.
  • Loading branch information
perrutquist authored and andreasnoack committed Jun 24, 2018
1 parent 948b088 commit 41d7bcc
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 6 deletions.
15 changes: 11 additions & 4 deletions stdlib/LinearAlgebra/src/eigen.jl
Original file line number Diff line number Diff line change
Expand Up @@ -210,10 +210,17 @@ julia> eigvals(diag_matrix)
"""
eigvals(A::StridedMatrix{T}; permute::Bool=true, scale::Bool=true) where T =
eigvals!(copy_oftype(A, eigtype(T)), permute = permute, scale = scale)
function eigvals(x::T; kwargs...) where T<:Number
val = convert(eigtype(T), x)
return imag(val) == 0 ? [real(val)] : [val]
end

"""
For a scalar input, `eigvals` will return a scalar.
# Example
```jldoctest
julia> eigvals(-2)
-2
```
"""
eigvals(x::Number; kwargs...) = imag(x) == 0 ? real(x) : x

"""
eigmax(A; permute::Bool=true, scale::Bool=true)
Expand Down
4 changes: 2 additions & 2 deletions stdlib/LinearAlgebra/test/symmetric.jl
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ end
d, v = eigen(asym)
@test asym*v[:,1] d[1]*v[:,1]
@test v*Diagonal(d)*transpose(v) asym
@test isequal(eigvals(asym[1]), eigvals(asym[1:1,1:1]))
@test isequal(eigvals(asym[1]), eigvals(asym[1:1,1:1])[1])
@test abs.(eigen(Symmetric(asym), 1:2).vectors'v[:,1:2]) Matrix(I, 2, 2)
@test abs.(eigen(Symmetric(asym), d[1] - 1, (d[2] + d[3])/2).vectors'v[:,1:2]) Matrix(I, 2, 2)
@test eigvals(Symmetric(asym), 1:2) d[1:2]
Expand All @@ -234,7 +234,7 @@ end
d, v = eigen(aherm)
@test aherm*v[:,1] d[1]*v[:,1]
@test v*Diagonal(d)*v' aherm
@test isequal(eigvals(aherm[1]), eigvals(aherm[1:1,1:1]))
@test isequal(eigvals(aherm[1]), eigvals(aherm[1:1,1:1])[1])
@test abs.(eigen(Hermitian(aherm), 1:2).vectors'v[:,1:2]) Matrix(I, 2, 2)
@test abs.(eigen(Hermitian(aherm), d[1] - 1, (d[2] + d[3])/2).vectors'v[:,1:2]) Matrix(I, 2, 2)
@test eigvals(Hermitian(aherm), 1:2) d[1:2]
Expand Down

0 comments on commit 41d7bcc

Please sign in to comment.