user10830069
user10830069

Reputation: 21

scipy.optimize.minimize returns a solution that does not satisfied constraints of the problem. Why?

scipy.optimize.minimize produces solution that does not satisfy the constraints, but the report says that optimization terminated successfully.

The objective is (x[0] - 3)**2 + (x[1] - 2)**2

The constraint is x[0]+x[1]<=4

The correct solution should be [2.5, 1.5]

The answer from the function is [3,2]

I tried different optimization methods. Tried no methods. Tried variations on the syntax.

Here is the code (super simple, it seems):

import numpy as np
from scipy import optimize

def f(x):
    return (x[0] - 3)**2 + (x[1] - 2)**2

def con(x):
    return sum(x)-4 

x0 = np.array([0, 0])
res=optimize.minimize(f, x0, method="SLSQP",constraints={"fun": con, "type": "ineq"}, options={'disp':True}) 
print(res)
print(sum(res.x)-4)

Upvotes: 0

Views: 1250

Answers (1)

user10830069
user10830069

Reputation: 21

ineq is a >= 0 inequality. I assumed (based on the examples I have seen) that it is <=0 inequality. Indeed, the code below, after correcting for this misinterpretation, produces the correct answer.

import numpy as np from scipy import optimize

def f(x): return (x[0] - 3)**2 + (x[1] - 2)**2

def con(x): return 4-sum(x)

x0 = np.array([0, 0]) res=optimize.minimize(f, x0, method="SLSQP",constraints={"fun": con, "type": "ineq"}, options={'disp':True}) print(res) print(sum(res.x)-4)

Upvotes: 2

Related Questions