Skip to content

Commit 37aa43a

Browse files
jishnubKristofferC
authored andcommitted
Restrict Diagonal sqrt branch to positive diag (#1203)
As noted in #1193, the `sqrt(::Digonal{<:Real})` method requires the diagonal element to be positive, so that `sqrt` is defined for the individual elements. We therefore may restrict the diagonal branch in the dense `sqrt` method to matrices with positive `diag` if the `eltype` is `Real`. Fixes #1193 After this, ```julia julia> A = diagm(0 => [1.0, -1.0]) 2×2 Matrix{Float64}: 1.0 0.0 0.0 -1.0 julia> sqrt(A) 2×2 Matrix{ComplexF64}: 1.0+0.0im 0.0+0.0im 0.0+0.0im 0.0+1.0im ``` (cherry picked from commit 16d9d61)
1 parent 87542a7 commit 37aa43a

File tree

2 files changed

+8
-1
lines changed

2 files changed

+8
-1
lines changed

src/dense.jl

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -972,7 +972,8 @@ sqrt(::AbstractMatrix)
972972
function sqrt(A::AbstractMatrix{T}) where {T<:Union{Real,Complex}}
973973
if checksquare(A) == 0
974974
return copy(float(A))
975-
elseif isdiag(A)
975+
elseif isdiag(A) && (T <: Complex || all(x -> x zero(x), diagview(A)))
976+
# Real Diagonal sqrt requires each diagonal element to be positive
976977
return applydiagonal(sqrt, A)
977978
elseif ishermitian(A)
978979
sqrtHermA = sqrt(Hermitian(A))

test/dense.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -984,6 +984,12 @@ end
984984
@testset "sqrt for diagonal" begin
985985
A = diagm(0 => [1, 2, 3])
986986
@test sqrt(A)^2 A
987+
988+
A = diagm(0 => [1.0, -1.0])
989+
@test sqrt(A) == diagm(0 => [1.0, 1.0im])
990+
@test sqrt(A)^2 A
991+
B = im*A
992+
@test sqrt(B)^2 B
987993
end
988994

989995
@testset "issue #40141" begin

0 commit comments

Comments
 (0)