简体   繁体   中英

Why scipy.optimize.minimize does not work with a constraint and initial value 0

I am trying to optimize a function of two variables. I want one variable to be fixed at 50 and another be between -5 and 5. I wrote the following code:

x0 = np.array([50, 0.0])
res = minimize(error, x0, constraints=[
    {'type': "eq", "fun": lambda x: x[0] - 50},
    {'type': "ineq", "fun": lambda x: -abs(x[1]) + 5},
])

where minimize is a function from scipy.optimize . The first constraint is x[0] == 50 and second one is -5 <= x[1] <= 5 . I get the following response: message: 'Inequality constraints incompatible' . But when I set the second variable to be not zero (eg x0 = np.array([50, 0.1]) ) it finds a solution successfully. What can be the reason of such behavior?

The constraints need to be differentiable, and your second constraint is not. If you express the constraint in terms of x[1]**2 instead of abs(x[1]) , it should work. You could also eliminate the abs by splitting the constraint into two separate constraints, one for the upper bound and one for the lower bound.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM