Skip to content

Commit

Permalink
Add logabsdet(::Diagonal). (#32998)
Browse files Browse the repository at this point in the history
Works with generic eltypes. Fixes #32988.
  • Loading branch information
tpapp authored and andreasnoack committed Aug 21, 2019
1 parent 2502b8e commit 183cba4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
5 changes: 5 additions & 0 deletions stdlib/LinearAlgebra/src/diagonal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -664,3 +664,8 @@ cholesky(A::Diagonal, ::Val{false} = Val(false); check::Bool = true) =
cholesky!(cholcopy(A), Val(false); check = check)

Base._sum(A::Diagonal, ::Colon) = sum(A.diag)

function logabsdet(A::Diagonal)
mapreduce(x -> (log(abs(x)), sign(x)), ((d1, s1), (d2, s2)) -> (d1 + d2, s1 * s2),
A.diag)
end
19 changes: 16 additions & 3 deletions stdlib/LinearAlgebra/test/diagonal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -322,10 +322,15 @@ Random.seed!(1)
@test(transpose(D) * vv == D * vv)
end

#logdet
# logdet and logabsdet
if relty <: Real
ld=convert(Vector{relty},rand(n))
@test logdet(Diagonal(ld)) logdet(Matrix(Diagonal(ld)))
lD = Diagonal(convert(Vector{relty}, rand(n)))
lM = Matrix(lD)
@test logdet(lD) logdet(lM)
d1, s1 = @inferred logabsdet(lD)
d2, s2 = logabsdet(lM)
@test d1 d2
@test s1 == s2
end

@testset "similar" begin
Expand Down Expand Up @@ -595,4 +600,12 @@ end
@test sum(Diagonal([1,2,3])) == 6
end

@testset "logabsdet for generic eltype" begin
d = Any[1, -2.0, -3.0]
D = Diagonal(d)
d1, s1 = logabsdet(D)
@test d1 sum(log abs, d)
@test s1 == prod(sign, d)
end

end # module TestDiagonal

0 comments on commit 183cba4

Please sign in to comment.