+3 votes
in Programming Languages by (60.0k points)
I have a function of one variable (e.g. x^2 - 2x +1). I want to find the value that minimizes the function and the function's minimum value. How can I do this in Python?

1 Answer

+2 votes
by (354k points)
selected by
 
Best answer

SciPy optimize provides functions for minimizing (or maximizing) a given objective function. If your function is a scalar function of one variable, you can use the minimize_scalar() function to find the minimum value of the function and the value that minimizes it.

A scalar function is a function of one or more variables that returns a scalar output(a single value).
E.g. f(x) = x^2 - 2x + 1 is a scalar function of one variable.

Here is the python code to find the value of x between -1 and 5 that minimizes the objective function.

from scipy.optimize import minimize_scalar

def objfun(x):
    return x ** 2 - 2 * x + 1

res = minimize_scalar(objfun, method='bounded', bounds=(-1, 5))
print(res)

The above code prints the following output:

    fun: 0.0
 message: 'Solution found.'
    nfev: 6
  status: 0
 success: True
       x: 1.0

The output shows that the minimum value of the function is 0 and x=1 minimizes this function.


...