Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find minimum and maximum values of a function

I have a function and I would like to find its maximum and minimum values. My function is this:

def function(x, y):
    exp = (math.pow(x, 2) + math.pow(y, 2)) * -1
    return math.exp(exp) * math.cos(x * y) * math.sin(x * y)

I have an interval for x [-1, 1] and y [-1, 1]. I would like to find a way, limited to this interval, to discover the max and min values of this function.

like image 515
pceccon Avatar asked Sep 23 '13 17:09

pceccon


People also ask

What are the minimum and maximum values of the function?

Here, the maximum value f(x) at x = 1 is called the absolute maximum value, global maximum or greatest value of the function f on the closed interval [0, 1]. Similarly, the minimum value of f(x) at x = 0 is called the absolute minimum value, global minimum or least value of the function f on the closed interval [0, 1].

How do you find minimum value of a function?

You can find this minimum value by graphing the function or by using one of the two equations. If you have the equation in the form of y = ax^2 + bx + c, then you can find the minimum value using the equation min = c - b^2/4a.

How do you find the maximum of a function?

If you are given the formula y = ax2 + bx + c, then you can find the maximum value using the formula max = c - (b2 / 4a). If you have the equation y = a(x-h)2 + k and the a term is negative, then the maximum value is k.


1 Answers

Using, for instance, scipy's fmin (which contains an implementation of the Nelder-Mead algorithm), you can try this:

import numpy as np
from scipy.optimize import fmin
import math

def f(x):
    exp = (math.pow(x[0], 2) + math.pow(x[1], 2)) * -1
    return math.exp(exp) * math.cos(x[0] * x[1]) * math.sin(x[0] * x[1])

fmin(f,np.array([0,0]))

which yields the following output:

Optimization terminated successfully.
     Current function value: -0.161198
     Iterations: 60
     Function evaluations: 113 
array([ 0.62665701, -0.62663095])

Please keep in mind that:

1) with scipy you need to convert your function into a function accepting an array (I showed how to do it in the example above);

2) fmin uses, like most of its pairs, an iterative algorithm, therefore you must provide a starting point (in my example, I provided (0,0)). You can provide different starting points to obtain different minima/maxima.

like image 102
Emanuele Bezzi Avatar answered Oct 16 '22 15:10

Emanuele Bezzi