Skip to content

Commit

Permalink
Improve efficiency of minimum/maximum(::Diagonal) (#30236)
Browse files Browse the repository at this point in the history
```
julia> DM = Diagonal(rand(100));

julia> @Btime minimum($DM);    # before
  27.987 μs (0 allocations: 0 bytes)

julia> @Btime minimum($DM);    # after
  246.091 ns (0 allocations: 0 bytes)
```
  • Loading branch information
jlapeyre authored Oct 25, 2023
1 parent 3b1ba62 commit bb138fa
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
12 changes: 12 additions & 0 deletions stdlib/LinearAlgebra/src/diagonal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,18 @@ end
r
end

function Base.minimum(D::Diagonal{T}) where T <: Number
mindiag = minimum(D.diag)
size(D, 1) > 1 && return (min(zero(T), mindiag))
return mindiag
end

function Base.maximum(D::Diagonal{T}) where T <: Number
maxdiag = Base.maximum(D.diag)
size(D, 1) > 1 && return (max(zero(T), maxdiag))
return maxdiag
end

@inline function getindex(D::Diagonal, i::Int, j::Int)
@boundscheck checkbounds(D, i, j)
if i == j
Expand Down
6 changes: 6 additions & 0 deletions stdlib/LinearAlgebra/test/diagonal.jl
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,12 @@ Random.seed!(1)
for func in (det, tr)
@test func(D) func(DM) atol=n^2*eps(relty)*(1+(elty<:Complex))
end

if eltype(D) <: Real
@test minimum(D) minimum(DM)
@test maximum(D) maximum(DM)
end

if relty <: BlasFloat
for func in (exp, cis, sinh, cosh, tanh, sech, csch, coth)
@test func(D) func(DM) atol=n^3*eps(relty)
Expand Down

0 comments on commit bb138fa

Please sign in to comment.