python-scipyHow do I use Python's Scipy library to minimize a scalar?
To use Python's Scipy library to minimize a scalar, you need to first import the minimize
function from the scipy.optimize
module.
from scipy.optimize import minimize
Then, define the objective function you want to minimize. This should be a function that takes a single argument and returns the value of the scalar you want to minimize.
def objective_function(x):
return x ** 2
Next, define the bounds of the scalar you want to minimize. This is done using a tuple of two numbers, where the first number is the lower bound and the second number is the upper bound.
bounds = (-5, 5)
Finally, call the minimize
function with the objective function and bounds as arguments. The minimize
function returns an object containing the optimal value of the scalar and other information.
result = minimize(objective_function, bounds=bounds)
print(result)
fun: 1.9242640687119285e-16
hess_inv: <2x2 LbfgsInvHessProduct with dtype=float64>
jac: array([-3.55271368e-15, 0.00000000e+00])
message: b'CONVERGENCE: NORM_OF_PROJECTED_GRADIENT_<=_PGTOL'
nfev: 6
nit: 2
status: 0
success: True
x: array([-3.55271368e-15, -3.55271368e-15])
The optimal value of the scalar is 1.9242640687119285e-16
, which is the fun
attribute of the result
object.
Code explanation
**
from scipy.optimize import minimize
- imports theminimize
function from thescipy.optimize
module.def objective_function(x):
- defines the objective function you want to minimize.bounds = (-5, 5)
- defines the bounds of the scalar you want to minimize.result = minimize(objective_function, bounds=bounds)
- calls theminimize
function with the objective function and bounds as arguments.print(result)
- prints theresult
object containing the optimal value of the scalar and other information.
## Helpful links
More of Python Scipy
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
- How can I check if a certain version of Python is compatible with SciPy?
- How do I use the trapz function in Python SciPy?
- How do I create a 2D array of zeros using Python and NumPy?
- How can I use Python and SciPy to read and write WAV files?
- How do I convert a Python numpy array to a list?
- How do I use the NumPy transpose function in Python?
- How do I use the scipy ttest_ind function in Python?
- How can I use Python and SciPy to implement a quantum Monte Carlo simulation?
See more codes...