Issue with data type in Arrays

I am new to Julia and have been recommended to post here for questions about my Julia related work.

Here is my code that attempts to create a stochastic SIR model: https://paste.ofcode.org/riNhvYWMcaxUwP9PU6wKm6 but I get the following error:

InexactError: Int64(18.45312925286407)

Stacktrace:
[1] Int64 at .\float.jl:709 [inlined]
[2] convert at .\number.jl:7 [inlined]
[3] push! at .\array.jl:868 [inlined]
[4] stochasticSIR(::Array{Float64,1}, ::Array{Float64,1}, ::Int64) at .\In[18]:33
[5] top-level scope at In[18]:51

This apparently means that a Float64 number is trying to be converted into an integer. I do not know where in my code that is done. How is this fixed and why is this happening?

1 Like

The stack trace points to line 33:

 push!(sirData.time, sirData.time[end] + k) # time step by k

and, indeed, you’ve initialized sirData.time to be [0] on line 17 which makes it a vector of ints. But k is a float (from the previous line).

What happens when you change that to

sirData = (dataₛ = [initialState[1]], dataᵢ = [initialState[2]], dataᵣ = [initialState[3]], time = [0.0])

?

Also, you don’t need semicolons as line / statement terminators.

Here’s a MWE:

julia> k = rand(Exponential(1/0.2))
3.1726199691536108

julia> a = [0]
1-element Array{Int64,1}:
 0

julia> push!(a, k)
ERROR: InexactError: Int64(3.1726199691536108)
...

julia> a = [0.0]
1-element Array{Float64,1}:
 0.0

julia> push!(a, k)
2-element Array{Float64,1}:
 0.0
 3.1726199691536108
1 Like

@sbromberger Thank you, that fixed that issue. I actually did not realize that the “33” on line [4] meant line 33 in the stochasticSIR function. I will note that for future debugging.

I have another question, but if I need to make a thread for it please just say so.

I wrote this code to be my interpretation of http://epirecip.es/epicookbook/chapters/sir-stochastic-discretestate-continuoustime/julia but it is not doing what I thought it would do since when I examine each array in the sirOutput tuple they do not have matching lengths nor does the data they contain make sense. At this point the issue is a fundamental problem with how my code operates and I do not know what flaw in my architecture is. Do you?

Your example code is relatively small. Have you tried stepping through it with Debugger.jl to find the point where it’s execution diverges from your expectation?

This is getting to be more complex than I have time for, but

if randNum < (probᵢ / probₜ)
            push!(sirData.dataₛ, sirData.dataₛ[end] - 1);
            push!(sirData.dataᵢ, sirData.dataᵢ[end] + 1);
        else
            push!(sirData.dataᵢ, sirData.dataᵢ[end] - 1);
            push!(sirData.dataᵣ, sirData.dataᵣ[end] +1)
        end

pretty much guarantees that the data\_x arrays will be of different lengths: you’re pushing to data\i in both cases, but only pushing to the others conditionally.

1 Like