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?