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 theminimizefunction from the SciPy library.def quadratic(x):- defines a function calledquadraticthat 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 theminimizefunction with thequadraticfunction and an initial guess ofx0=0.print(result)- prints the result of theminimizefunction.
Helpful links
More of Python Scipy
- How do I uninstall Python Scipy?
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python and SciPy to find the zeros of a function?
- How do I use Scipy zeros in Python?
- How can I use Python Scipy to zoom in on an image?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How can I use Python and Numpy to parse XML data?
- How do I download a Python Scipy .whl file?
- How can I use Python and Numpy to zip files?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
See more codes...