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 can I check if a certain version of Python is compatible with SciPy?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How do I create a 2D array of zeros using Python and NumPy?
- How do I use Python Scipy to perform a Z test?
- How do I check the version of Python Scipy I am using?
- How do I uninstall Python Scipy?
- How do I update Python SciPy?
- How do I use the NumPy transpose function in Python?
- How do I use the scipy ttest_ind function in Python?
- How do I upgrade my Python Scipy package?
See more codes...