1

I am given an objective function that I need to maximize using a nonlinear optimizer in Python. I understand that many optimizers are written as minimizations but I am having trouble setting up the parameters given that I have a few inequality constraints to be met. I checked the roots of my objective function using Wolfram Alpha optimizer and have x = 1.86121 and y = 1.07457.

I am also planning to check these roots and find the Lagrangian multipliers using the Lagrangian approach. Does anyone know how to setup this optimization problem using Scipy.optimize. I believe I have to set up the constraints as separate functions but I do not know how. Thank you.

Objective function: maximize 5-x^2-xy-3y^2

Subject to constraints: x>=0, y>=0, and xy >=2

eruiz
  • 59
  • 9

1 Answers1

4
import numpy as np
import scipy.optimize

def obj(x):
    return -1 * (5 - x[0]**2 - x[0]*x[1] - 3*x[1]**2)

def cons(x):
    return x[0]*x[1] - 2

result = scipy.optimize.minimize(fun = obj, x0 = [1, 1], bounds=[(0, np.inf), (0, np.inf)], constraints={"fun": cons, "type": "ineq"})

Check this.

enesdemirag
  • 325
  • 1
  • 10
  • I see your logic but the output is wrong. Why didn't you add the constraints the ```x[0] and x[1] >= 0``` ? – eruiz Aug 05 '20 at 19:45
  • 2
    Those constraints are in the `bound` parameter. The objective function has a typo: it should be `- (5 - x[0]**2 - x[0]*x[1] - 3*x[1]**2)` – FBruzzesi Aug 06 '20 at 07:07
  • 1
    Thanks @FBruzzesi. I fixed the typo and now it works. – enesdemirag Aug 06 '20 at 15:21
  • @enesdemirag Thank you so much, it worked! You're both too kind – eruiz Aug 06 '20 at 16:07
  • @enesdemirag Hello. I did this optimization like you showed and I get why you did what you did. But doing the math on paper I see that the result is a negative number for this optimization. Conceptually speaking if we minimize a function and it is a positive number is this the same as the maximization being a negative number? I know math I promise but the introduction of optimizers kinda confuses me – eruiz Aug 08 '20 at 17:37
  • 1
    Minimizing f(x) and taking result as negative is different than minimizing -f(x). @eruiz – enesdemirag Aug 09 '20 at 09:26