root#
- scipy.optimize.root(fun,x0,args=(),method='hybr',jac=None,tol=None,callback=None,options=None)[source]#
Find a root of a vector function.
- Parameters:
- funcallable
A vector function to find a root of.
Suppose the callable has signature
f0(x,*my_args,**my_kwargs), wheremy_argsandmy_kwargsare required positional and keyword arguments.Rather than passingf0as the callable, wrap it to acceptonlyx; e.g., passfun=lambdax:f0(x,*my_args,**my_kwargs)as thecallable, wheremy_args(tuple) andmy_kwargs(dict) have beengathered before invoking this function.- x0ndarray
Initial guess.
- argstuple, optional
Extra arguments passed to the objective function and its Jacobian.
- methodstr, optional
Type of solver. Should be one of
‘hybr’(see here)
‘lm’(see here)
‘broyden1’(see here)
‘broyden2’(see here)
‘anderson’(see here)
‘linearmixing’(see here)
‘diagbroyden’(see here)
‘excitingmixing’(see here)
‘krylov’(see here)
‘df-sane’(see here)
- jacbool or callable, optional
Ifjac is a Boolean and is True,fun is assumed to return thevalue of Jacobian along with the objective function. If False, theJacobian will be estimated numerically.jac can also be a callable returning the Jacobian offun. Inthis case, it must accept the same arguments asfun.
- tolfloat, optional
Tolerance for termination. For detailed control, use solver-specificoptions.
- callbackfunction, optional
Optional callback function. It is called on every iteration as
callback(x,f)wherex is the current solution andfthe corresponding residual. For all methods but ‘hybr’ and ‘lm’.- optionsdict, optional
A dictionary of solver options. E.g.,xtol ormaxiter, see
show_options()for details.
- Returns:
- solOptimizeResult
The solution represented as a
OptimizeResultobject.Important attributes are:xthe solution array,successaBoolean flag indicating if the algorithm exited successfully andmessagewhich describes the cause of the termination. SeeOptimizeResultfor a description of other attributes.
See also
show_optionsAdditional options accepted by the solvers
Notes
This section describes the available solvers that can be selected by the‘method’ parameter. The default method ishybr.
Methodhybr uses a modification of the Powell hybrid method asimplemented in MINPACK[1].
Methodlm solves the system of nonlinear equations in a least squaressense using a modification of the Levenberg-Marquardt algorithm asimplemented in MINPACK[1].
Methoddf-sane is a derivative-free spectral method.[3]
Methodsbroyden1,broyden2,anderson,linearmixing,diagbroyden,excitingmixing,krylov are inexact Newton methods,with backtracking or full line searches[2]. Each method correspondsto a particular Jacobian approximations.
Methodbroyden1 uses Broyden’s first Jacobian approximation, it isknown as Broyden’s good method.
Methodbroyden2 uses Broyden’s second Jacobian approximation, itis known as Broyden’s bad method.
Methodanderson uses (extended) Anderson mixing.
MethodKrylov uses Krylov approximation for inverse Jacobian. Itis suitable for large-scale problem.
Methoddiagbroyden uses diagonal Broyden Jacobian approximation.
Methodlinearmixing uses a scalar Jacobian approximation.
Methodexcitingmixing uses a tuned diagonal Jacobianapproximation.
Warning
The algorithms implemented for methodsdiagbroyden,linearmixing andexcitingmixing may be useful for specificproblems, but whether they will work may depend strongly on theproblem.
Added in version 0.11.0.
References
[2]C. T. Kelley. 1995. Iterative Methods for Linear and NonlinearEquations. Society for Industrial and Applied Mathematics.DOI:10.1137/1.9781611970944
[3]W. La Cruz, J.M. Martinez, M. Raydan.Math. Comp. 75, 1429 (2006).
Examples
The following functions define a system of nonlinear equations and itsjacobian.
>>>importnumpyasnp>>>deffun(x):...return[x[0]+0.5*(x[0]-x[1])**3-1.0,...0.5*(x[1]-x[0])**3+x[1]]
>>>defjac(x):...returnnp.array([[1+1.5*(x[0]-x[1])**2,...-1.5*(x[0]-x[1])**2],...[-1.5*(x[1]-x[0])**2,...1+1.5*(x[1]-x[0])**2]])
A solution can be obtained as follows.
>>>fromscipyimportoptimize>>>sol=optimize.root(fun,[0,0],jac=jac,method='hybr')>>>sol.xarray([ 0.8411639, 0.1588361])
Large problem
Suppose that we needed to solve the following integrodifferentialequation on the square\([0,1]\times[0,1]\):
\[\nabla^2 P = 10 \left(\int_0^1\int_0^1\cosh(P)\,dx\,dy\right)^2\]with\(P(x,1) = 1\) and\(P=0\) elsewhere on the boundary ofthe square.
The solution can be found using the
method='krylov'solver:>>>fromscipyimportoptimize>>># parameters>>>nx,ny=75,75>>>hx,hy=1./(nx-1),1./(ny-1)
>>>P_left,P_right=0,0>>>P_top,P_bottom=1,0
>>>defresidual(P):...d2x=np.zeros_like(P)...d2y=np.zeros_like(P)......d2x[1:-1]=(P[2:]-2*P[1:-1]+P[:-2])/hx/hx...d2x[0]=(P[1]-2*P[0]+P_left)/hx/hx...d2x[-1]=(P_right-2*P[-1]+P[-2])/hx/hx......d2y[:,1:-1]=(P[:,2:]-2*P[:,1:-1]+P[:,:-2])/hy/hy...d2y[:,0]=(P[:,1]-2*P[:,0]+P_bottom)/hy/hy...d2y[:,-1]=(P_top-2*P[:,-1]+P[:,-2])/hy/hy......returnd2x+d2y-10*np.cosh(P).mean()**2
>>>guess=np.zeros((nx,ny),float)>>>sol=optimize.root(residual,guess,method='krylov')>>>print('Residual:%g'%abs(residual(sol.x)).max())Residual: 5.7972e-06 # may vary
>>>importmatplotlib.pyplotasplt>>>x,y=np.mgrid[0:1:(nx*1j),0:1:(ny*1j)]>>>plt.pcolormesh(x,y,sol.x,shading='gouraud')>>>plt.colorbar()>>>plt.show()
