InexactError in Callback

When I learn the user-cut callback function ,I rewrite the code below:

function user_cut()
    Random.seed!(13)
    N = 30
    capacity = 10
    weights,values = rand(N),rand(N)
    model = Model(GLPK.Optimizer)
    @variable(model,x[1:N],Bin)
    @constraint(model,weights' * x <= capacity)
    @objective(model,Max,x' * values)
    
    function call_back(cb_data)
        x_val = callback_value.(cb_data,x)
        total = weights' * x_val
        println("callback total : $(total)")
#         num = sum(1 for i in 1:N if x_val[i] > 1e-4)
        num = sum(Int,x_val)
        if total > capacity
            con = @build_constraint(sum(x) <= num - 1)
            println("add $(con)")
            MOI.submit(model,MOI.UserCut(cb_data),con)
        end
    end
    set_attribute(model,MOI.UserCutCallback(),call_back)
    optimize!(model)
    sum(value.(x))
end

This is the official code:

num = sum(1 for i in 1:N if x_val[i] > 1e-4)

But When I change it to :

sum(Int,x_val)

It raised error:

callback total : 10.0
InexactError: Int64(23.047802735569988)

Can somebody explain why?

You are requesting conversion from a Float64 to an Int64 and no exact conversion exists.

julia> Int(23.0478)
ERROR: InexactError: Int64(23.0478)
Stacktrace:
 [1] Int64(x::Float64)
   @ Base ./float.jl:900
 [2] top-level scope
   @ REPL[33]:1

julia> Int(23.0)
23

Perhaps you mean

num = sum(trunc, x_val)
2 Likes

Other options are num = sum(x_val .> 1e-4) or num = sum(round.(Int, x_val)).

But really, there’s nothing wrong with what you wrote to begin with.