我正在努力修改Julia-specific tutorial on NLopt以满足我的需求,如果有人可以解释我在做什么错或无法理解,我将不胜感激。
我希望:
myfunc(x)
的值;在哪里x
必须位于单位超立方体中(在下面的示例中只有2个维度);和x
的元素之和必须为一个。在下面,我使myfunc
非常简单-从x
到[2.0, 0.0]
的距离的平方,这样,对于该问题,显而易见的正确解决方案是{{1} 1}}。我还添加了x = [1.0,0.0]
语句,以便可以看到求解器在做什么。
myfunc(x) = 1.0
我已经阅读了this similar question和文档here和here,但是仍然无法弄清楚出了什么问题。令人担忧的是,每次运行println
时,我都会看到不同的行为,as in this screenshot包括求解器多次无用评估testNLopt = function()
origin = [2.0,0.0]
n = length(origin)
#Returns square of the distance between x and "origin", and amends grad in-place
myfunc = function(x::Vector{Float64}, grad::Vector{Float64})
if length(grad) > 0
grad = 2 .* (x .- origin)
end
xOut = sum((x .- origin).^2)
println("myfunc: x = $x; myfunc(x) = $xOut; ∂myfunc/∂x = $grad")
return(xOut)
end
#Constrain the sums of the x's to be 1...
sumconstraint =function(x::Vector{Float64}, grad::Vector{Float64})
if length(grad) > 0
grad = ones(length(x))
end
xOut = sum(x) - 1
println("sumconstraint: x = $x; constraint = $xOut; ∂constraint/∂x = $grad")
return(xOut)
end
opt = Opt(:LD_SLSQP,n)
lower_bounds!(opt, zeros(n))
upper_bounds!(opt,ones(n))
equality_constraint!(opt,sumconstraint,0)
#xtol_rel!(opt,1e-4)
xtol_abs!(opt,1e-8)
min_objective!(opt, myfunc)
maxeval!(opt,20)#to ensure code always terminates, remove this line when code working correctly?
optimize(opt,ones(n)./n)
end
的情况。