Julia+JuMP: variable number of arguments to function

℡╲_俬逩灬. 提交于 2019-12-05 13:33:44

As explained in http://jump.readthedocs.io/en/latest/nlp.html#raw-expression-input , objective functions can be given without the macro. The relevant expression:

    JuMP.setNLobjective(m, :Min, Expr(:call, :myf, [x[i] for i=1:n]...))

is even simpler than the @eval based one and works in the function. The code is:

using JuMP, Ipopt

function testme(n)
    myf(a...) = sum(collect(a).^2)

    m = JuMP.Model(solver=Ipopt.IpoptSolver())

    JuMP.register(m, :myf, n, myf, autodiff=true)
    @JuMP.variable(m, x[1:n] >= 0.5)

    JuMP.setNLobjective(m, :Min, Expr(:call, :myf, [x[i] for i=1:n]...))
    JuMP.solve(m)
    return [getvalue(x[i]) for i=1:n]
end

testme(3)

and it returns:

julia> testme(3)

:

 EXIT: Optimal Solution Found.
3-element Array{Float64,1}:
 0.5
 0.5
 0.5
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!