Search code examples
pythonscipymathematical-optimization

Maximize objective function using scipy.optimize


The scipy.optimize module has scipy.optimize.minimize which allows to find value that minimize an objective function. But there is no scipy.optimize.maximize. Why? How do I solve a maximization problem using SciPy?


Solution

  • To maximize f, we minimize -f. A mini-example, maximizing f which is the sine function:

    from scipy.optimize import minimize
    import numpy as np
    f = lambda x: np.sin(x)  # function to be MAXIMIZED
    res = minimize(lambda x: -f(x), 0)
    print('Maximum {} attained at {}'.format(-res.fun, res.x))
    

    prints "Maximum 1.0 attained at [1.57079632]".