Skip to content

DimensionError for determinant of generic, triangular, unitful matricesΒ #1415

@lxvm

Description

@lxvm
using Unitful
using LinearAlgebra
det([1 0; 0 1]*u"m")

leads to

ERROR: DimensionError: m and 1 mΒ² are not dimensionally compatible.
Stacktrace:
 [1] convert(::Type{Quantity{Float64, 𝐋, Unitful.FreeUnits{(m,), 𝐋, nothing}}}, x::Quantity{Int64, 𝐋², Unitful.FreeUnits{(mΒ²,), 𝐋², nothing}})
   @ Unitful ~/.julia/packages/Unitful/sxiHA/src/conversion.jl:133
 [2] det(A::Matrix{Quantity{Int64, 𝐋, Unitful.FreeUnits{(m,), 𝐋, nothing}}})
   @ LinearAlgebra ~/.julia/juliaup/julia-1.11.6+0.aarch64.apple.darwin14/share/julia/stdlib/v1.11/LinearAlgebra/src/generic.jl:1649
 [3] top-level scope
   @ REPL[24]:1

I suspect that it is because this type handling should be using oneunit instead of one

S = promote_type(T, typeof((one(T)*zero(T) + zero(T))/one(T)))

Although it isn't entirely clear to me why conversion is necessary, here is a potential fix that keeps the code similar but fixes this edge case

function mydet(A::AbstractMatrix{T}) where {T}
    if istriu(A) || istril(A)
        S = promote_type(T, typeof((oneunit(T)*zero(T) + zero(T)*zero(T))/one(T)))
        return convert(S, det(UpperTriangular(A)))
    end
    return det(lu(A; check = false))
end
mydet([1 0; 0 1]*u"m") # returns 1.0 mΒ²

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions