Finding the maximum of a function

I think scipy.optimize.minimize_scalar and scipy.optimize.minimize are the preferred ways now, that give you access to the range of techniques, e.g.

solution = scipy.optimize.minimize_scalar(lambda x: -f(x), bounds=[0,1], method='bounded')

for a single variable function that must lie between 0 and 1.


You can use scipy.optimize.fmin on the negative of your function.

def f(x): return -2 * x**2 + 4 * x
max_x = scipy.optimize.fmin(lambda x: -f(x), 0)
# array([ 1.])

If your function is solvable analytically try SymPy. I'll use EMS's example above.

In [1]: from sympy import *
In [2]: x = Symbol('x', real=True)

In [3]: f = -2 * x**2 + 4*x

In [4]: fprime = f.diff(x)
In [5]: fprime
Out[5]: -4*x + 4

In [6]: solve(fprime, x) # solve fprime = 0 with respect to x
Out[6]: [1]

Of course, you'll still need to check that 1 is a maximizer and not a minimizer of f

In [7]: f.diff(x).diff(x) < 0
Out[7]: True

Tags:

Python

Numpy