Skip to content

Matrix identity not calling one() ? #659

Closed
@Lecrapouille

Description

Hi, I'm trying to implement the max-plus semiring algebra in Julia 1.0.3 like the follow code:

struct MP{T} <: Number val::T end
Base.:+(a::MP, b::MP) = MP(max(a.val, b.val))
Base.:*(a::MP, b::MP) = MP(a.val + b.val)
Base.show(io::IO, k::MP) = show(io, k.val)
Base.convert(::MP{T}, x) where T = MP(T(x))
Base.zero(::MP{T}) where T = MP(typemin(T))
Base.one(::MP{T}) where T = MP(zero(T))
Base.zero(::Type{MP{T}}) where T = MP(typemin(T))
Base.one(::Type{MP{T}}) where T = MP(zero(T))
mparray(A::Array) = map(MP, A)

The following code gives the expected behavior :

julia> Base.zero(MP{Float64})
-Inf

julia> Base.one(MP{Float64})
0.0

But the following code does not gives the expected behavior :

julia> Matrix{MP{Float64}}(I, 2, 2)
2×2 Array{MP{Float64},2}:
  1.0  -Inf
 -Inf   1.0

What I was expected:

julia> Matrix{MP{Float64}}(I, 2, 2)
2×2 Array{MP{Float64},2}:
  0.0  -Inf
 -Inf   0.0

I think Matrix{MP{Float64}}(I, 2, 2) creates a matrix initialized by Base.zero(MP{Float64}) calling MP(typemin(Float64)) giving -Inf but the I does not create the diagonal initialized by one(MP{Float64}) which would called MP(zero(Float64)) giving 0.0.

I followed this link JuliaLang/julia#30298 so fortunatly I can fix by writting code like this:

julia> Matrix{MP{Float64}}(0I, 2, 2)
2×2 Array{MP{Float64},2}:
  0.0  -Inf
 -Inf   0.0

Is it because I use Bool that I have this behavior ? And how to replace code 0I by one(MP{Float64})I ? I really think that Julia shall implement I calling one() and without giving Type::T calls one(Bool).

I'm starting learning julia! Thx!

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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