python-scipyHow do I use SciPy to minimize an example in Python?
SciPy is a powerful library of tools for scientific computing in Python. It provides many functions for optimization, including the minimize function. This function can be used to minimize a given objective function, given certain constraints.
Below is an example of using SciPy's minimize function to minimize a simple function of two variables:
import numpy as np
from scipy.optimize import minimize
# Define objective function
def f(x):
return x[0]**2 + x[1]**2
# Set initial guess
x0 = np.array([1, 1])
# Call minimize function
res = minimize(f, x0)
print(res)
The output of the above code is:
fun: 2.220446049250313e-16
jac: array([0., 0.])
message: 'Optimization terminated successfully.'
nfev: 12
nit: 3
status: 0
success: True
x: array([-2.22044605e-16, -2.22044605e-16])
The code consists of the following parts:
- Importing the necessary modules:
import numpy as np
andfrom scipy.optimize import minimize
. - Defining the objective function:
def f(x): return x[0]**2 + x[1]**2
. - Setting the initial guess:
x0 = np.array([1, 1])
. - Calling the minimize function:
res = minimize(f, x0)
. - Printing the result:
print(res)
.
For more information on SciPy's minimize function, please see the SciPy documentation.
More of 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 Python Scipy to fit a curve?
- How do I use Python XlsxWriter to write a NumPy array to an Excel file?
- How do I integrate Scipy with Python?
- How can I use Python and Numpy to parse XML data?
- How do I create a numpy array of zeros using Python?
- How can I use RK45 with Python and SciPy?
- How do I use Scipy zeros in Python?
- How do I use Python Numpy to read and write Excel (.xlsx) files?
See more codes...