1

I am trying to solve a simple set of equations in sympy. Finding the solution manually is simple, but I want to do it with sympy to learn the tool.

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])

The code above gives me the error NotImplementedError: inequality has more than one symbol of interest..

Question 1: Why is this? The inequality only contains xand not lamda.

Question 2: Is it possible to solve the same problem in another way, using sympy?


The background of the problem, if you are interested

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

.. and then applying stationarity and primal feasibility from KKT conditions

LudvigH
  • 3,662
  • 5
  • 31
  • 49
  • `solve` only solves systems of equalities. It cannot handle inequalities. Regarding the solution to your problem, you have omitted the important "complementary slackness" equality. I would propose to use `solve` to find a solution of the system of equalities included in the KKT conditions and then "manually" identify which solution(s) satisfy the inequalities. – Stelios Apr 12 '19 at 11:46

1 Answers1

0

As mentioned in the comments, sympy.solve solves for system of equalities. So it should be,

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) 

Edit: Now from the extremum points you have to find the minimum.

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)
Nihal Sangeeth
  • 5,168
  • 2
  • 17
  • 32
  • Since this solution assumes the optimum is at the boundary, it won't hold in general. I cannot accept it. :( – LudvigH Apr 13 '19 at 07:39