Search code examples
pythonoptimizationscipyminimizationscipy-optimize

Optimizing a function using Scipy Package


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


Solution

  • 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.