在Sympy中解决简单的凸优化

时间:2019-04-12 09:30:38

标签: python sympy mathematical-optimization

我正在尝试用sympy解决一组简单的方程式。手动找到解决方案很简单,但是我想通过sympy来学习该工具。

from sympy import symbols,solve,Le,Eq
l,x = symbols('lamda x')
f0 = x**2+1
f1 = (x-2)*(x-4); feasible_set = Le(f1,0);
lagrange = f0 + l*f1
stationary_lagrangian = Eq(lagrange.diff(x),0)
solve([feasible_set,stationary_lagrangian])

上面的代码给我错误NotImplementedError: inequality has more than one symbol of interest.

问题1 :为什么?不等式仅包含x,不包含lamda

问题2 :是否可以使用sympy以另一种方式解决相同的问题?


问题的背景(如果有兴趣的话)

minimize (over x \in R)
    x^2 + 1
subject to
    (x-2)(x-4) <= 0

..然后应用KKT conditions

中的平稳性和原始可行性

1 个答案:

答案 0 :(得分:0)

如评论中所述,sympy.solve求解均等系统。应该是

from sympy import solve, var, symbols, diff
x = var('x',real=True);
f = x**2+1
g = (x-2)*(x-4)

l = symbols('lambda', real = True)
lagrange = f - l* g
grad = [diff(lagrange,x)]
kkt_eqs = grad + [g]
extremum_points = solve(kkt_eqs, [x, l], dict=True) 

编辑:现在,您必须从极值点中找到最小值。

f_x_ = min(ele[x]**2 + 1 for ele in stationary_points)
minimum = [ele[x] for ele in stationary_points if ele[x]**2+1 == f_x_]
print(minimum)