Skip to content

Commit a10ca67

Browse files
authored
setting zero values in distmx with zero(T) (#230)
1 parent 2011e0d commit a10ca67

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed

src/shortestpaths/bellman-ford.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ function bellman_ford_shortest_paths(
4141
active[sources] .= true
4242
dists = fill(typemax(T), nvg)
4343
parents = zeros(U, nvg)
44-
dists[sources] .= 0
44+
dists[sources] .= zero(T)
4545
no_changes = false
4646
new_active = falses(nvg)
4747

test/shortestpaths/bellman-ford.jl

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,4 +41,37 @@
4141
@test_throws Graphs.NegativeCycleError bellman_ford_shortest_paths(g, 1, d)
4242
@test has_negative_edge_cycle(g, d)
4343
end
44+
45+
# setting zeros with zero(T)
46+
struct CustomReal <: Real
47+
val::Float64
48+
bias::Int # need this, to avoid auto conversion of CustomReal(0)
49+
end
50+
Base.zero(::T) where {T<:CustomReal} = zero(T)
51+
Base.zero(::Type{CustomReal}) = CustomReal(0.0, 4)
52+
Base.typemax(::T) where {T<:CustomReal} = typemax(T)
53+
Base.typemax(::Type{CustomReal}) = CustomReal(typemax(Float64), 0)
54+
Base.:+(a::CustomReal, b::CustomReal) = CustomReal(a.val + b.val, 0)
55+
Base.:<(a::CustomReal, b::CustomReal) = a.val < b.val
56+
57+
d3 = [CustomReal(i, 3) for i in d1]
58+
d4 = sparse(d3)
59+
for g in testdigraphs(g4)
60+
y = @inferred(bellman_ford_shortest_paths(g, 2, d3))
61+
z = @inferred(bellman_ford_shortest_paths(g, 2, d4))
62+
@test getfield.(y.dists, :val) == getfield.(z.dists, :val) == [Inf, 0, 6, 17, 33]
63+
@test @inferred(enumerate_paths(z))[2] == []
64+
@test @inferred(enumerate_paths(z))[4] == enumerate_paths(z, 4) == [2, 3, 4]
65+
@test @inferred(!has_negative_edge_cycle(g))
66+
@test @inferred(!has_negative_edge_cycle(g, d3))
67+
68+
y = @inferred(bellman_ford_shortest_paths(g, 2, d3))
69+
z = @inferred(bellman_ford_shortest_paths(g, 2, d4))
70+
@test getfield.(y.dists, :val) == getfield.(z.dists, :val) == [Inf, 0, 6, 17, 33]
71+
@test @inferred(enumerate_paths(z))[2] == []
72+
@test @inferred(enumerate_paths(z))[4] == enumerate_paths(z, 4) == [2, 3, 4]
73+
@test @inferred(!has_negative_edge_cycle(g))
74+
z = @inferred(bellman_ford_shortest_paths(g, 2))
75+
@test z.dists == [typemax(Int), 0, 1, 2, 3]
76+
end
4477
end

0 commit comments

Comments
 (0)