python-scipyHow can I use Python Scipy to optimize a root?
Scipy provides a number of optimization algorithms for finding a root of a function. The scipy.optimize.root
function is the most general and provides a variety of methods for finding a root.
For example, the following code will use the broyden1
method to find the root of a function:
import scipy.optimize as opt
def f(x):
return x**2 - 4
result = opt.root(f, x0=1, method='broyden1')
print(result)
The output of this code will be:
converged: True
flag: 'converged'
fun: array([0.])
jac: array([-8.88178420e-16])
message: 'The solution converged.'
nfev: 9
root: array([2.])
The code consists of the following parts:
import scipy.optimize as opt
imports thescipy.optimize
module and assigns it to the nameopt
.def f(x):
defines a functionf
with one argumentx
.return x**2 - 4
returns the value ofx**2 - 4
whenf
is called.result = opt.root(f, x0=1, method='broyden1')
calls thescipy.optimize.root
function with the functionf
, an initial guess ofx0=1
, and thebroyden1
method.print(result)
prints the result of the optimization.
For more information, see the Scipy root documentation.
More of Python Scipy
- How do I create a 2D array of zeros using Python and NumPy?
- How can I check if a certain version of Python is compatible with SciPy?
- How to use Python, XML-RPC, and NumPy together?
- How can I use Python and SciPy to find the zeros of a function?
- How do I use Python Scipy to perform a Z test?
- 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 do I use Python and SciPy to write a WAV file?
- How do I use the scipy ttest_ind function in Python?
- How do I convert a Python Numpy array to a list?
See more codes...