Skip to content

Commit

Permalink
zero for OneElement (#332)
Browse files Browse the repository at this point in the history
* zero for OneElement

* Specialize iszero

* Specialize isone

* Return a OneElement instead of a Zero
  • Loading branch information
jishnub authored Jul 9, 2024
1 parent 4bfbeec commit 1896e30
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
11 changes: 11 additions & 0 deletions src/oneelement.jl
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,17 @@ Base.@propagate_inbounds function Base.setindex(A::AbstractZeros{T,N}, v, kj::Va
OneElement(convert(T, v), kj, axes(A))
end

zero(A::OneElement) = OneElement(zero(A.val), A.ind, A.axes)

iszero(A::OneElement) = iszero(getindex_value(A))

function isone(A::OneElementMatrix)
lenA = length(A)
lenA == 0 && return true
lenA > 1 && return false
isone(getindex_value(A))
end

*(x::OneElement, b::Number) = OneElement(x.val * b, x.ind, x.axes)
*(b::Number, x::OneElement) = OneElement(b * x.val, x.ind, x.axes)
/(x::OneElement, b::Number) = OneElement(x.val / b, x.ind, x.axes)
Expand Down
22 changes: 22 additions & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2501,6 +2501,28 @@ end
@test A / (2 + 3.0im) === OneElement(val / (2 + 3.0im), (2,2), (3,4)) == B / (2 + 3.0im)
end

@testset "zero/iszero" begin
v = OneElement(10, 3, 4)
@test v + zero(v) == v
@test typeof(zero(v)) == typeof(v)

@test !iszero(v)
@test iszero(OneElement(0, 3, 4))
@test iszero(OneElement(0, 5, 4))
@test iszero(OneElement(3, (2,2), (0,0)))
@test iszero(OneElement(3, (2,2), (1,2)))

v = OneElement(SMatrix{2,2}(1:4), 3, 4)
@test v + zero(v) == v
@test typeof(zero(v)) == typeof(v)
end

@testset "isone" begin
@test isone(OneElement(3, (0,0), (0,0)))
@test isone(OneElement(1, (1,1), (1,1)))
@test !isone(OneElement(2, (1,1), (1,1)))
@test !isone(OneElement(1, (2,2), (2,2)))
end

@testset "tril/triu" begin
for A in (OneElement(3, (4,2), (4,5)), OneElement(3, (2,3), (4,5)), OneElement(3, (3,3), (4,5)))
Expand Down

0 comments on commit 1896e30

Please sign in to comment.