我正在尝试将 Matlab fmincon 优化函数转换为 julia。但没有太多的运气。
我认为可以使用 NLopt 或 IPopt。默认示例有效,但是当我尝试更改值时,它似乎没有迭代。
using NLopt
count = 0 # keep track of # function evaluations
function myfunc(x::Vector, grad::Vector)
if length(grad) > 0
grad[1] = 0
grad[2] = 0.5/sqrt(x[2])
end
global count
count::Int += 1
println("f_$count($x)")
sqrt(x[2])
end
function myconstraint(x::Vector, grad::Vector, a, b)
if length(grad) > 0
grad[1] = 3a * (a*x[1] + b)^2
grad[2] = -1
end
(a*x[1] + b)^3 - x[2]
end
opt = Opt(:LD_MMA, 2)
lower_bounds!(opt, [-Inf, 0.])
xtol_rel!(opt,1e-4)
min_objective!(opt, myfunc)
inequality_constraint!(opt, (x,g) -> myconstraint(x,g,2,0), 1e-8)
inequality_constraint!(opt, (x,g) -> myconstraint(x,g,-1,1), 1e-8)
(minf,minx,ret) = optimize(opt, [1.234, 5.678])
println("got $minf at $minx after $count iterations (returned $ret)")
这个工作正常。它给出了 2 个结果和 11 次迭代
using NLopt
count = 0 # keep track of # function evaluations
function myfunc(x)
x[1]^2 + 5*x[2] - 3
end
function myconstraint(x)
100*x[1] + 2000*x[2] == 100
end
opt = Opt(:LD_MMA, 2)
lower_bounds!(opt, [0, 0])
upper_bounds!(opt,[10,5])
xtol_rel!(opt,1e-10)
min_objective!(opt, myfunc);
inequality_constraint!(opt, (x) -> myconstraint(x), 1e-10)
(minf,minx,ret) = optimize(opt, [0.1,0.1])
这不起作用,它只是给出一个结果和 0 次迭代
using NLopt
count = 0 # keep track of # function evaluations
function myfunc(x::Vector, grad::Vector)
x[1]^2 + 5*x[2] - 3
end
function myconstraint(result::Vector, x::Vector, grad::Vector)
100*x[1] + 2000*x[2] == 100
end
opt = Opt(:LD_MMA, 2)
lower_bounds!(opt, [0., 0.])
upper_bounds!(opt, [10.,5.])
xtol_rel!(opt,1e-4)
min_objective!(opt, myfunc)
inequality_constraint!(opt, (x,g) -> myconstraint(x), 1e-8)
(minf,minx,ret) = optimize(opt, [0., 0.])#even with [5.,10.]
这只是给了我一个结果和 0 次迭代。
有人知道我做错了什么吗?