python-scipyHow do I use Python's SciPy library to minimize a function?
Using SciPy's minimize
function, it is possible to minimize a function. The minimize
function requires at least two arguments: the function to be minimized, and an initial guess for the minimum. The following example code block shows how to use the minimize
function to minimize a simple quadratic function:
from scipy.optimize import minimize
def quadratic(x):
return x**2 + 5*x + 4
result = minimize(quadratic, x0=0)
print(result)
The output of this code is:
fun: -3.0000000000011435
jac: array([-2.05395529e-07])
message: 'Optimization terminated successfully.'
nfev: 9
nit: 2
status: 0
success: True
x: array([-2.99999995e+00])
The parts of this code are as follows:
from scipy.optimize import minimize
- imports theminimize
function from the SciPy library.def quadratic(x):
- defines a function calledquadratic
that takes a single argumentx
.return x**2 + 5*x + 4
- returns the value of the quadratic function for the given argumentx
.result = minimize(quadratic, x0=0)
- calls theminimize
function with thequadratic
function and an initial guess ofx0=0
.print(result)
- prints the result of theminimize
function.
Helpful links
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How do I calculate variance using Python and SciPy?
- How can I use Python and SciPy to find the zeros of a function?
- How can I use Python Scipy to zoom in on an image?
- How can I use the x.shape function in Python Numpy?
- How do I create a zero matrix using Python and Numpy?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I use Python and SciPy to create a tutorial PDF?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How do I use the scipy ttest_ind function in Python?
See more codes...