Skip to content

Commit 1cfda3f

Browse files
authored
Strong zero in Diagonal triple multiplication (#55927)
Currently, triple multiplication with a `LinearAlgebra.BandedMatrix` sandwiched between two `Diagonal`s isn't associative, as this is implemented using broadcasting, which doesn't assume a strong zero, whereas the two-term matrix multiplication does. ```julia julia> D = Diagonal(StepRangeLen(NaN, 0, 3)); julia> B = Bidiagonal(1:3, 1:2, :U); julia> D * B * D 3×3 Matrix{Float64}: NaN NaN NaN NaN NaN NaN NaN NaN NaN julia> (D * B) * D 3×3 Bidiagonal{Float64, Vector{Float64}}: NaN NaN ⋅ ⋅ NaN NaN ⋅ ⋅ NaN julia> D * (B * D) 3×3 Bidiagonal{Float64, Vector{Float64}}: NaN NaN ⋅ ⋅ NaN NaN ⋅ ⋅ NaN ``` This PR ensures that the 3-term multiplication is evaluated as a sequence of two-term multiplications, which fixes this issue. This also improves performance, as only the bands need to be evaluated now. ```julia julia> D = Diagonal(1:1000); B = Bidiagonal(1:1000, 1:999, :U); julia> @Btime $D * $B * $D; 656.364 μs (11 allocations: 7.63 MiB) # v"1.12.0-DEV.1262" 2.483 μs (12 allocations: 31.50 KiB) # This PR ```
1 parent 06e7b9d commit 1cfda3f

File tree

2 files changed

+13
-0
lines changed

2 files changed

+13
-0
lines changed

stdlib/LinearAlgebra/src/special.jl

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,8 @@ for op in (:+, :-)
112112
end
113113
end
114114

115+
(*)(Da::Diagonal, A::BandedMatrix, Db::Diagonal) = _tri_matmul(Da, A, Db)
116+
115117
# disambiguation between triangular and banded matrices, banded ones "dominate"
116118
_mul!(C::AbstractMatrix, A::AbstractTriangular, B::BandedMatrix, alpha::Number, beta::Number) =
117119
@stable_muladdmul _mul!(C, A, B, MulAddMul(alpha, beta))

stdlib/LinearAlgebra/test/diagonal.jl

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1265,6 +1265,17 @@ end
12651265
@test *(Diagonal(ones(n)), Diagonal(1:n), Diagonal(ones(n)), Diagonal(1:n)) isa Diagonal
12661266
end
12671267

1268+
@testset "triple multiplication with a sandwiched BandedMatrix" begin
1269+
D = Diagonal(StepRangeLen(NaN, 0, 4));
1270+
B = Bidiagonal(1:4, 1:3, :U)
1271+
C = D * B * D
1272+
@test iszero(diag(C, 2))
1273+
# test associativity
1274+
C1 = (D * B) * D
1275+
C2 = D * (B * D)
1276+
@test diag(C,2) == diag(C1,2) == diag(C2,2)
1277+
end
1278+
12681279
@testset "diagind" begin
12691280
D = Diagonal(1:4)
12701281
M = Matrix(D)

0 commit comments

Comments
 (0)