L iS ddlZddlmZddlZddlmZddlmZddlZ dZ dZ de je jzZgd ZdZd Zd Zd Zd ZdZdZdZdZdZdZeeeeeeeeeeiZGddeZdZdZdZ d+dZ!dZ"de ee ddfdZ#de ee ddfdZ$de ee ddfdZ%de ee ddfd Z&ee fd!Z'd"Z(d#Z) d,d$Z*d%Z+d&Z,d'Z-Gd(d)Z.dde ee ddfd*Z/y)-N) namedtuple)_zeros)OptimizeResultdg-=)newtonbisectridderbrentqbrenthtoms748 RootResults convergedz sign errorzconvergence errorz value errorzNo errorceZdZdZdZy)raRepresents the root finding result. Attributes ---------- root : float Estimated root location. iterations : int Number of iterations needed to find the root. function_calls : int Number of times the function was called. converged : bool True if the routine converged. flag : str Description of the cause of termination. method : str Root finding method used. c||_||_||_|tk(|_|t vrt ||_||_y||_||_yN)root iterationsfunction_calls _ECONVERGEDrflag_mapflagmethod)selfrrrrrs ^/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/optimize/_zeros_py.py__init__zRootResults.__init__7sP $,, 8  DI DI N)__name__ __module__ __qualname____doc__r!r"r rr#s & r"rc@|r|\}}}}t|||||}||fS|S)Nrrrrrr full_outputrrxfuncallsrrresultss r results_cr1Cs;()%8Z1)3-5#'8'zr"c@|\}}}}|rt|||||}||fS|S)z:Select from a tuple of (root, funccalls, iterations, flag)r)r*r+s r _results_selectr3Os;$%!AxT1)3-5#'8'z Hr"c$fdd_S)Nc|g|}xjdz c_tj|r+d|d}t|}||_j|_||S)NrzThe function value at x=z is NaN; solver cannot continue.)_function_callsnpisnan ValueError_x)r.argsfxmsgerrff_raises r r@z _wrap_nan_raise..f_raise]sg q[4[1$ 88B<-aS1--CS/CCF")"9"9C I r"r)r6)r?r@s`@r _wrap_nan_raiserA[s  G Nr"r'FTc |dkrtd|ddtj|}|dkr tdtj|dkDrt |||||||| Stj |ddz}|} d} |#d } t|D]}|| g|}| dz } |dk(rt| | | |tf| cS|| g|}| dz } |dk(rTd }| r|d |dzd | d z }t|tj|tdt| | | |dztf| cS||z }|r;|| g|}| dz } d} ||z|z dz }tj|dkr|d|z z}| |z }tj || ||rt| || |dztf| cS|} nrd} |||k(r td|}nd}|d|zz}||dk\r|n| z }|| g|}| dz } ||g|}| dz } t|t|kr || ||f\} }}}t|D]}||k(rh|| k7rAd|| z d}| r|d |dzd |d z }t|tj|td|| zdz }t| || |dztf| cSt|t|kDr| |z |z| zd||z z z }n| |z | z|zd||z z z }tj ||||rt| || |dztf| cS||}} |}||g|}| dz } | rddzd d }t|t| | dztf| S)ay Find a root of a real or complex function using the Newton-Raphson (or secant or Halley's) method. Find a root of the scalar-valued function `func` given a nearby scalar starting point `x0`. The Newton-Raphson method is used if the derivative `fprime` of `func` is provided, otherwise the secant method is used. If the second order derivative `fprime2` of `func` is also provided, then Halley's method is used. If `x0` is a sequence with more than one item, `newton` returns an array: the roots of the function from each (scalar) starting point in `x0`. In this case, `func` must be vectorized to return a sequence or array of the same shape as its first argument. If `fprime` (`fprime2`) is given, then its return must also have the same shape: each element is the first (second) derivative of `func` with respect to its only variable evaluated at each element of its first argument. `newton` is for finding roots of a scalar-valued functions of a single variable. For problems involving several variables, see `root`. Parameters ---------- func : callable The function whose root is wanted. It must be a function of a single variable of the form ``f(x,a,b,c...)``, where ``a,b,c...`` are extra arguments that can be passed in the `args` parameter. x0 : float, sequence, or ndarray An initial estimate of the root that should be somewhere near the actual root. If not scalar, then `func` must be vectorized and return a sequence or array of the same shape as its first argument. fprime : callable, optional The derivative of the function when available and convenient. If it is None (default), then the secant method is used. args : tuple, optional Extra arguments to be used in the function call. tol : float, optional The allowable error of the root's value. If `func` is complex-valued, a larger `tol` is recommended as both the real and imaginary parts of `x` contribute to ``|x - x0|``. maxiter : int, optional Maximum number of iterations. fprime2 : callable, optional The second order derivative of the function when available and convenient. If it is None (default), then the normal Newton-Raphson or the secant method is used. If it is not None, then Halley's method is used. x1 : float, optional Another estimate of the root that should be somewhere near the actual root. Used if `fprime` is not provided. rtol : float, optional Tolerance (relative) for termination. full_output : bool, optional If `full_output` is False (default), the root is returned. If True and `x0` is scalar, the return value is ``(x, r)``, where ``x`` is the root and ``r`` is a `RootResults` object. If True and `x0` is non-scalar, the return value is ``(x, converged, zero_der)`` (see Returns section for details). disp : bool, optional If True, raise a RuntimeError if the algorithm didn't converge, with the error message containing the number of iterations and current function value. Otherwise, the convergence status is recorded in a `RootResults` return object. Ignored if `x0` is not scalar. *Note: this has little to do with displaying, however, the `disp` keyword cannot be renamed for backwards compatibility.* Returns ------- root : float, sequence, or ndarray Estimated location where function is zero. r : `RootResults`, optional Present if ``full_output=True`` and `x0` is scalar. Object containing information about the convergence. In particular, ``r.converged`` is True if the routine converged. converged : ndarray of bool, optional Present if ``full_output=True`` and `x0` is non-scalar. For vector functions, indicates which elements converged successfully. zero_der : ndarray of bool, optional Present if ``full_output=True`` and `x0` is non-scalar. For vector functions, indicates which elements had a zero derivative. See Also -------- root_scalar : interface to root solvers for scalar functions root : interface to root solvers for multi-input, multi-output functions Notes ----- The convergence rate of the Newton-Raphson method is quadratic, the Halley method is cubic, and the secant method is sub-quadratic. This means that if the function is well-behaved the actual error in the estimated root after the nth iteration is approximately the square (cube for Halley) of the error after the (n-1)th step. However, the stopping criterion used here is the step size and there is no guarantee that a root has been found. Consequently, the result should be verified. Safer algorithms are brentq, brenth, ridder, and bisect, but they all require that the root first be bracketed in an interval where the function changes sign. The brentq algorithm is recommended for general use in one dimensional problems when such an interval has been found. When `newton` is used with arrays, it is best suited for the following types of problems: * The initial guesses, `x0`, are all relatively the same distance from the roots. * Some or all of the extra arguments, `args`, are also arrays so that a class of similar problems can be solved together. * The size of the initial guesses, `x0`, is larger than O(100) elements. Otherwise, a naive loop may perform as well or better than a vector. Examples -------- >>> import numpy as np >>> import matplotlib.pyplot as plt >>> from scipy import optimize >>> def f(x): ... return (x**3 - 1) # only one real root at x = 1 ``fprime`` is not provided, use the secant method: >>> root = optimize.newton(f, 1.5) >>> root 1.0000000000000016 >>> root = optimize.newton(f, 1.5, fprime2=lambda x: 6 * x) >>> root 1.0000000000000016 Only ``fprime`` is provided, use the Newton-Raphson method: >>> root = optimize.newton(f, 1.5, fprime=lambda x: 3 * x**2) >>> root 1.0 Both ``fprime2`` and ``fprime`` are provided, use Halley's method: >>> root = optimize.newton(f, 1.5, fprime=lambda x: 3 * x**2, ... fprime2=lambda x: 6 * x) >>> root 1.0 When we want to find roots for a set of related starting values and/or function parameters, we can provide both of those as an array of inputs: >>> f = lambda x, a: x**3 - a >>> fder = lambda x, a: 3 * x**2 >>> rng = np.random.default_rng() >>> x = rng.standard_normal(100) >>> a = np.arange(-50, 50) >>> vec_res = optimize.newton(f, x, fprime=fder, args=(a, ), maxiter=200) The above is the equivalent of solving for each value in ``(x, a)`` separately in a for-loop, just faster: >>> loop_res = [optimize.newton(f, x0, fprime=fder, args=(a0,), ... maxiter=200) ... for x0, a0 in zip(x, a)] >>> np.allclose(vec_res, loop_res) True Plot the results found for all values of ``a``: >>> analytical_result = np.sign(a) * np.abs(a)**(1/3) >>> fig, ax = plt.subplots() >>> ax.plot(a, analytical_result, 'o') >>> ax.plot(a, vec_res, '.') >>> ax.set_xlabel('$a$') >>> ax.set_ylabel('$x$ where $f(x, a)=0$') >>> plt.show() rztol too small (g <= 0)rmaxiter must be greater than 0r'?r zDerivative was zero.z Failed to converge after z iterations, value is . stacklevelhalleyrtolatolsecantzx1 and x0 must be differentg-C6?z Tolerance of z reached.@zFailed to converge after )r9operatorindexr7size _array_newtonasarrayranger3r RuntimeErrorwarningswarnRuntimeWarning _ECONVERRabsisclose)funcx0fprimer;tolmaxiterfprime2x1rMr,dispp0r/ritrfvalfderr= newton_stepfder2adjpp1epsq0q1s r r r msSd ax?3q'899nnW%G{9:: wwr{QT2vtS'7(* * B c !B BH >' C?T?D MHqy&"h[!A6KK"$t$D MHqy,4S1WI>%%'D+C's++ c>a@&"ha!CVMM+K*T*A !"E)D01466#;?39,K[ Azz!Rd5&!XsQw !DfNNBO' T >Rx !>??BCq3wB "'3t ,B "_t_A  "_t_A  r7SW R^NBB> CRx8)"r') 1`` is ``True``. For docstring, see `newton`. T)copy)dtyperrF?gQ?rrPrHzRMS of rCz reachedrIallsomesz derivatives were zeroz failed to converge after dz iterationsresult)rrzero_der)r7array ones_likeboolrVrUanyastype result_typefloat64r\finfofloatrowheresqrtsumrXrYrZrwrWr)r^r_r`r;rarbrcr,rmfailuresnz_der iterationrhridprkdxrnrprqactiveactive_zero_derr| nonzero_dpzero_der_nz_dprms all_or_somer=r{s r rTrTs $A||AT*H \\( #F w I::d1ntn-D88:;;t,::fQ../DaiF::<fV ,B" 71#4t#453rE&M!9DL!HHI 1BNN1b"**$EFA fIOI!vvbzS0HV F#'')/ 4XXe_ $ & !b&\BHHQ!VR"5 5 ZZQ ' ZZR$ (at,w -IBhF::<!VsNQ-(BGV+<'J&3N!!#ggN+a.??AEF Awh7TUV$,<<>%vK O#9:C MM#~! < '||~e6 Q9'!KP <<>s# # c>a8H&GH 1xi * Hr"c (t|ts|f}tj|}|dkrt d|dd|t krt d|ddt ddt |}tj||||||||| } t|| dS) a Find root of a function within an interval using bisection. Basic bisection routine to find a root of the function `f` between the arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same signs. Slow but sure. Parameters ---------- f : function Python function returning a number. `f` must be continuous, and f(a) and f(b) must have opposite signs. a : scalar One end of the bracketing interval [a,b]. b : scalar The other end of the bracketing interval [a,b]. xtol : number, optional The computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The parameter must be positive. rtol : number, optional The computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The parameter cannot be smaller than its default value of ``4*np.finfo(float).eps``. maxiter : int, optional If convergence is not achieved in `maxiter` iterations, an error is raised. Must be >= 0. args : tuple, optional Containing extra arguments for the function `f`. `f` is called by ``apply(f, (x)+args)``. full_output : bool, optional If `full_output` is False, the root is returned. If `full_output` is True, the return value is ``(x, r)``, where x is the root, and r is a `RootResults` object. disp : bool, optional If True, raise RuntimeError if the algorithm didn't converge. Otherwise, the convergence status is recorded in a `RootResults` return object. Returns ------- root : float Root of `f` between `a` and `b`. r : `RootResults` (present if ``full_output = True``) Object containing information about the convergence. In particular, ``r.converged`` is True if the routine converged. Notes ----- As mentioned in the parameter documentation, the computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. In equation form, this terminating condition is ``abs(x - x0) <= xtol + rtol * abs(x0)``. The default value ``xtol=2e-12`` may lead to surprising behavior if one expects `bisect` to always compute roots with relative error near machine precision. Care should be taken to select `xtol` for the use case at hand. Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the highest level of accuracy. Larger values of `xtol` may be useful for saving function evaluations when a root is at or near zero in applications where the tiny absolute differences available between floating point numbers near zero are not meaningful. Examples -------- >>> def f(x): ... return (x**2 - 1) >>> from scipy import optimize >>> root = optimize.bisect(f, 0, 2) >>> root 1.0 >>> root = optimize.bisect(f, -2, 0) >>> root -1.0 See Also -------- brentq, brenth, bisect, newton fixed_point : scalar fixed-point finder fsolve : n-dimensional root-finding elementwise.find_root : efficient elementwise 1-D root-finder rxtol too small (rCrDrtol too small ( < )r ) isinstancetuplerQrRr9_rtolrAr_bisectr1 r?abr;xtolrMrbr,rer-s r r r sv dE "wnnW%G qy+D86:;; e|+D83uQiqABBAq!QdGT;MA [!X ..r"c (t|ts|f}tj|}|dkrt d|dd|t krt d|ddt ddt |}tj||||||||| } t|| dS) a Find a root of a function in an interval using Ridder's method. Parameters ---------- f : function Python function returning a number. f must be continuous, and f(a) and f(b) must have opposite signs. a : scalar One end of the bracketing interval [a,b]. b : scalar The other end of the bracketing interval [a,b]. xtol : number, optional The computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The parameter must be positive. rtol : number, optional The computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The parameter cannot be smaller than its default value of ``4*np.finfo(float).eps``. maxiter : int, optional If convergence is not achieved in `maxiter` iterations, an error is raised. Must be >= 0. args : tuple, optional Containing extra arguments for the function `f`. `f` is called by ``apply(f, (x)+args)``. full_output : bool, optional If `full_output` is False, the root is returned. If `full_output` is True, the return value is ``(x, r)``, where `x` is the root, and `r` is a `RootResults` object. disp : bool, optional If True, raise RuntimeError if the algorithm didn't converge. Otherwise, the convergence status is recorded in any `RootResults` return object. Returns ------- root : float Root of `f` between `a` and `b`. r : `RootResults` (present if ``full_output = True``) Object containing information about the convergence. In particular, ``r.converged`` is True if the routine converged. See Also -------- brentq, brenth, bisect, newton : 1-D root-finding fixed_point : scalar fixed-point finder elementwise.find_root : efficient elementwise 1-D root-finder Notes ----- Uses [Ridders1979]_ method to find a root of the function `f` between the arguments `a` and `b`. Ridders' method is faster than bisection, but not generally as fast as the Brent routines. [Ridders1979]_ provides the classic description and source of the algorithm. A description can also be found in any recent edition of Numerical Recipes. The routine used here diverges slightly from standard presentations in order to be a bit more careful of tolerance. As mentioned in the parameter documentation, the computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. In equation form, this terminating condition is ``abs(x - x0) <= xtol + rtol * abs(x0)``. The default value ``xtol=2e-12`` may lead to surprising behavior if one expects `ridder` to always compute roots with relative error near machine precision. Care should be taken to select `xtol` for the use case at hand. Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the highest level of accuracy. Larger values of `xtol` may be useful for saving function evaluations when a root is at or near zero in applications where the tiny absolute differences available between floating point numbers near zero are not meaningful. References ---------- .. [Ridders1979] Ridders, C. F. J. "A New Algorithm for Computing a Single Root of a Real Continuous Function." IEEE Trans. Circuits Systems 26, 979-980, 1979. Examples -------- >>> def f(x): ... return (x**2 - 1) >>> from scipy import optimize >>> root = optimize.ridder(f, 0, 2) >>> root 1.0 >>> root = optimize.ridder(f, -2, 0) >>> root -1.0 rrrCrDrrrr ) rrrQrRr9rrAr_ridderr1rs r r r WsJ dE "wnnW%G qy+D86:;; e|+D83uQiqABBAq!QdGT;MA [!X ..r"c (t|ts|f}tj|}|dkrt d|dd|t krt d|ddt ddt |}tj||||||||| } t|| dS) a Find a root of a function in a bracketing interval using Brent's method. Uses the classic Brent's method to find a root of the function `f` on the sign changing interval [a , b]. Generally considered the best of the rootfinding routines here. It is a safe version of the secant method that uses inverse quadratic extrapolation. Brent's method combines root bracketing, interval bisection, and inverse quadratic interpolation. It is sometimes known as the van Wijngaarden-Dekker-Brent method. Brent (1973) claims convergence is guaranteed for functions computable within [a,b]. [Brent1973]_ provides the classic description of the algorithm. Another description can be found in a recent edition of Numerical Recipes, including [PressEtal1992]_. A third description is at http://mathworld.wolfram.com/BrentsMethod.html. It should be easy to understand the algorithm just by reading our code. Our code diverges a bit from standard presentations: we choose a different formula for the extrapolation step. Parameters ---------- f : function Python function returning a number. The function :math:`f` must be continuous, and :math:`f(a)` and :math:`f(b)` must have opposite signs. a : scalar One end of the bracketing interval :math:`[a, b]`. b : scalar The other end of the bracketing interval :math:`[a, b]`. xtol : number, optional The computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The parameter must be positive. For nice functions, Brent's method will often satisfy the above condition with ``xtol/2`` and ``rtol/2``. [Brent1973]_ rtol : number, optional The computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The parameter cannot be smaller than its default value of ``4*np.finfo(float).eps``. For nice functions, Brent's method will often satisfy the above condition with ``xtol/2`` and ``rtol/2``. [Brent1973]_ maxiter : int, optional If convergence is not achieved in `maxiter` iterations, an error is raised. Must be >= 0. args : tuple, optional Containing extra arguments for the function `f`. `f` is called by ``apply(f, (x)+args)``. full_output : bool, optional If `full_output` is False, the root is returned. If `full_output` is True, the return value is ``(x, r)``, where `x` is the root, and `r` is a `RootResults` object. disp : bool, optional If True, raise RuntimeError if the algorithm didn't converge. Otherwise, the convergence status is recorded in any `RootResults` return object. Returns ------- root : float Root of `f` between `a` and `b`. r : `RootResults` (present if ``full_output = True``) Object containing information about the convergence. In particular, ``r.converged`` is True if the routine converged. See Also -------- fmin, fmin_powell, fmin_cg, fmin_bfgs, fmin_ncg : multivariate local optimizers leastsq : nonlinear least squares minimizer fmin_l_bfgs_b, fmin_tnc, fmin_cobyla : constrained multivariate optimizers basinhopping, differential_evolution, brute : global optimizers fminbound, brent, golden, bracket : local scalar minimizers fsolve : N-D root-finding brenth, ridder, bisect, newton : 1-D root-finding fixed_point : scalar fixed-point finder elementwise.find_root : efficient elementwise 1-D root-finder Notes ----- `f` must be continuous. f(a) and f(b) must have opposite signs. As mentioned in the parameter documentation, the computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. In equation form, this terminating condition is ``abs(x - x0) <= xtol + rtol * abs(x0)``. The default value ``xtol=2e-12`` may lead to surprising behavior if one expects `brentq` to always compute roots with relative error near machine precision. Care should be taken to select `xtol` for the use case at hand. Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the highest level of accuracy. Larger values of `xtol` may be useful for saving function evaluations when a root is at or near zero in applications where the tiny absolute differences available between floating point numbers near zero are not meaningful. References ---------- .. [Brent1973] Brent, R. P., *Algorithms for Minimization Without Derivatives*. Englewood Cliffs, NJ: Prentice-Hall, 1973. Ch. 3-4. .. [PressEtal1992] Press, W. H.; Flannery, B. P.; Teukolsky, S. A.; and Vetterling, W. T. *Numerical Recipes in FORTRAN: The Art of Scientific Computing*, 2nd ed. Cambridge, England: Cambridge University Press, pp. 352-355, 1992. Section 9.3: "Van Wijngaarden-Dekker-Brent Method." Examples -------- >>> def f(x): ... return (x**2 - 1) >>> from scipy import optimize >>> root = optimize.brentq(f, -2, 0) >>> root -1.0 >>> root = optimize.brentq(f, 0, 2) >>> root 1.0 rrrCrDrrrr ) rrrQrRr9rrAr_brentqr1rs r r r s| dE "wnnW%G qy+D86:;; e|+D83uQiqABBAq!QdGT;MA [!X ..r"c (t|ts|f}tj|}|dkrt d|dd|t krt d|ddt ddt |}tj||||||||| } t|| dS) aFind a root of a function in a bracketing interval using Brent's method with hyperbolic extrapolation. A variation on the classic Brent routine to find a root of the function f between the arguments a and b that uses hyperbolic extrapolation instead of inverse quadratic extrapolation. Bus & Dekker (1975) guarantee convergence for this method, claiming that the upper bound of function evaluations here is 4 or 5 times that of bisection. f(a) and f(b) cannot have the same signs. Generally, on a par with the brent routine, but not as heavily tested. It is a safe version of the secant method that uses hyperbolic extrapolation. The version here is by Chuck Harris, and implements Algorithm M of [BusAndDekker1975]_, where further details (convergence properties, additional remarks and such) can be found Parameters ---------- f : function Python function returning a number. f must be continuous, and f(a) and f(b) must have opposite signs. a : scalar One end of the bracketing interval [a,b]. b : scalar The other end of the bracketing interval [a,b]. xtol : number, optional The computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The parameter must be positive. As with `brentq`, for nice functions the method will often satisfy the above condition with ``xtol/2`` and ``rtol/2``. rtol : number, optional The computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The parameter cannot be smaller than its default value of ``4*np.finfo(float).eps``. As with `brentq`, for nice functions the method will often satisfy the above condition with ``xtol/2`` and ``rtol/2``. maxiter : int, optional If convergence is not achieved in `maxiter` iterations, an error is raised. Must be >= 0. args : tuple, optional Containing extra arguments for the function `f`. `f` is called by ``apply(f, (x)+args)``. full_output : bool, optional If `full_output` is False, the root is returned. If `full_output` is True, the return value is ``(x, r)``, where `x` is the root, and `r` is a `RootResults` object. disp : bool, optional If True, raise RuntimeError if the algorithm didn't converge. Otherwise, the convergence status is recorded in any `RootResults` return object. Returns ------- root : float Root of `f` between `a` and `b`. r : `RootResults` (present if ``full_output = True``) Object containing information about the convergence. In particular, ``r.converged`` is True if the routine converged. See Also -------- fmin, fmin_powell, fmin_cg, fmin_bfgs, fmin_ncg : multivariate local optimizers leastsq : nonlinear least squares minimizer fmin_l_bfgs_b, fmin_tnc, fmin_cobyla : constrained multivariate optimizers basinhopping, differential_evolution, brute : global optimizers fminbound, brent, golden, bracket : local scalar minimizers fsolve : N-D root-finding brentq, ridder, bisect, newton : 1-D root-finding fixed_point : scalar fixed-point finder elementwise.find_root : efficient elementwise 1-D root-finder Notes ----- As mentioned in the parameter documentation, the computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. In equation form, this terminating condition is ``abs(x - x0) <= xtol + rtol * abs(x0)``. The default value ``xtol=2e-12`` may lead to surprising behavior if one expects `brenth` to always compute roots with relative error near machine precision. Care should be taken to select `xtol` for the use case at hand. Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the highest level of accuracy. Larger values of `xtol` may be useful for saving function evaluations when a root is at or near zero in applications where the tiny absolute differences available between floating point numbers near zero are not meaningful. References ---------- .. [BusAndDekker1975] Bus, J. C. P., Dekker, T. J., "Two Efficient Algorithms with Guaranteed Convergence for Finding a Zero of a Function", ACM Transactions on Mathematical Software, Vol. 1, Issue 4, Dec. 1975, pp. 330-345. Section 3: "Algorithm M". :doi:`10.1145/355656.355659` Examples -------- >>> def f(x): ... return (x**2 - 1) >>> from scipy import optimize >>> root = optimize.brenth(f, -2, 0) >>> root -1.0 >>> root = optimize.brenth(f, 0, 2) >>> root 1.0 rrrCrDrrrr ) rrrQrRr9rrAr_brenthr1rs r r r Rsh dE "wnnW%G qy+D86:;; e|+D83uQiqABBAq!QdGT;MA [!X ..r"ctxrCttjxr#tfdt ddD }|S)Nc 3tK|]/\}}ttj||dzd1yw)rNrL)rr7r]).0i_frNfsrMs r z_notclose..s;52 2r!a%&z4HI5s58r)rwr7isfiniter enumerate)rrMrN notclosefvalss``` r _notclosersW G 5BKKO, 55!*2cr7!355 5 r"c|dd\}}|dd\}}||k(rtjStj|tj|kDr| |z |z|zd||z z z }|S| |z |z|zd||z z z }|S)z+Perform a secant step, taking a little careNrHr)r7nanr\)xvalsfvalsr_rdf0f1x2s r _secantrs2AYFB 2AYFB Rxvv  vvbzBFF2JcBhmb Qb[ 1 IcBhmb Qb[ 1 Ir"c|\}}tj|tj|zdkDrdnd}||||}}|||<|||<||fS)z?Update a bracket given (c, fc), return the discarded endpoints.rr)r7sign) abfabcfcfafbidxrxrfxs r _update_bracketrsZ FB bggbk)A-11Cgs3xBCHBsG s7Nr"c|r|rtj|}ntj|ddd}t|}||n t ||}tj ||g}|dd|dddf<t d|D]:}tj||dz d|dz f||d|d||z z z ||d|f<<|Stj|}tj|}tj|} |rdnd} || |d<t dt|D]K}|||t| zdz |dt| dz z } tj| dd| z } | | ||<M|S)aReturn a matrix of divided differences for the xvals, fvals pairs DD[i, j] = f[x_{i-j}, ..., x_i] for 0 <= j <= i If full is False, just return the main diagonal(or last row): f[a], f[a, b] and f[a, b, c]. If forward is False, return f[c], f[b, c], f[a, b, c].Nrrr)r7rUr}lenminzerosrVdiff) rrNfullforwardMDDrddrowidx2Usedenoms r _compute_divided_differencesrs~ JJu%EHHUODbD)E JAAq  XXq!f 81a4q! 6AAEFAEM!23)eFQUm35Bqr1uI 6 JJu E %B ((5/CqG 'NBqE 1c%j !aCH q()E-3s8a<,@@ggcl1o%G 1 Ir"ctj|}t|}tj||g}tj||g}|dd|dddf<|dd|dddf<t d|D]\}||d|dz f||dz |dz |dz fz }|d||z |||z }||d|z |z |z||d|f<|d||z |z |z |z||d|f<^tj |dddf|dzS)zCompute p(x) for the polynomial passing through the specified locations. Use Neville's algorithm to compute p(x) where p is the minimal degree polynomial passing through the points xvals, fvalsNrrr)rr)r7rUrrrVr) rrr.rQDkalphadiffiks r _interpolated_polyr!s1 JJu E E A !QA !QAAhAadGAhAadG 1a[8!"a!e) qQq1ua!e!344qQ%!*,!"IMV+e3!"a%&1q5MA%/%7!"a% 8 66!BF) qx ''r"c,t||||g||||gdS)zInverse cubic interpolation f-values -> x-values Given four points (fa, a), (fb, b), (fc, c), (fd, d) with fa, fb, fc, fd all distinct, find poly IP(y) through the 4 points and compute x=IP(0). r)r)rrrrzrrrfds r _inverse_poly_zeror5s$ r2r2.Aq! a @@r"c |\ |\}t |g||gdd\} fd} dk(r  z z }|Stj tjzdkDr n}t|D][} ||| d|z z z zzz z } |d| cxkr|dks)n|d|cxkr |dkr|cSt |dz }|S| }]|S) zApply Newton-Raphson like steps, using divided differences to approximate f' ab is a real interval [a, b] containing a root, fab holds the real values of f(a), f(b) d is a real number outside [ab, b] k is the number of steps to apply TFrrc,|z zz|z zzSrr')r.ABrrrs r _Pz_newton_quadratic.._PMs#QU aAE*R//r"rrHrrP)rr7rrVr)rrrzrrr_rr-rr1rrrrrs @@@@@r _newton_quadraticr?s DAq FB*Aq!9r2rl37eEGAq!00 Av QJ H''!*rwwr{*Q.QAq ARUa!q1uqy1}"5566BqEB&A&qEA%1%H&GcM HA  Hr"cheZdZdZdZdZdZdZdZddZ e fd Z d Z dd Z d ZdZd eededfdZy) TOMS748SolverzGSolve f(x, *args) == 0 using Algorithm748 of Alefeld, Potro & Shi. rurrcfd|_d|_d|_d|_d|_t j t j g|_t j t j g|_d|_ d|_ d|_ d|_ d|_ t|_t |_t$|_y)NrrHF)r?r;rrrr7rrrrzrefere_xtolrrrM_iterrb)rs r r!zTOMS748Solver.__init__is 66266"FFBFF#    r"c||_||_||_||_t ||j |_|j |jkDr=d|j}tj|td|j|_yy)Nztoms748: Overriding k: ->rvrI) rerrMrbmax_K_MINr_K_MAXrXrYrZ)rrrMrbrerr=s r configurezTOMS748Solver.configure|sp    Q $ 66DKK -dkk];C MM#~! <[[DF r"Tc|j|g|j}|xjdz c_tj|s|rt d|dd|d|S)z4Call the user-supplied function, update book-keepingrInvalid function value: f(r?) ->  )r?r;rr7rr9)rr.errorr<s r _callfzTOMS748Solver._callfs[ TVVA " " q {{259!AeB4qIJ J r"c6||j|j|fS)z/Package the result and statistics into a tuple.)rr)rr.rs r get_resultzTOMS748Solver.get_results4&&>>r"cFt|j|j||Sr)rrr)rrrs r rzTOMS748Solver._update_bracketstww!R88r"r'c d|_d|_||_||_||g|jddt j |rt j|dk7rtd|dt j |rt j|dk7rtd|d|j|}t j |rt j|dk7rtd|dd|d|dk(rt|fS|j|}t j |rt j|dk7rtd|dd|d|dk(rt|fSt j|t j|zdkDrtd|d d |d d |d d |d d ||g|jddtt|jd z fS) zPrepare for the iterations.rNzInvalid x value: rrr?rz/f(a) and f(b) must have different signs, but f(rz)=z, f(rP)rrr?r;rr7rimagr9rrrr _EINPROGRESSr)rr?rrr;rrs r startzTOMS748Solver.starts V {{1~q0156 6{{1~q0156 6 [[^{{2"''"+"29!AeB4qIJ J 7> ! [[^{{2"''"+"29!AeB4qIJ J 7> ! 772; $q (""#AbAd1Q%r"QqBC C2h S\C///r"cf|jdd\}}tj|||j|jrt t |jdz fS|j|jk\rtt |jdz fStt |jdz fS)zDetermine the current status.NrHrLrP) rr7r]rMrrrrrbr[r)rrrs r get_statuszTOMS748Solver.get_statusswwr{1 ::a ;DGG s 22 2 ??dll *c$''lS00 0S\C///r"c |xjdz c_tjtj}|j |j |j|jf\}}}}|jd|jdz }d}td|jdzD]}t|j||gzdd|zrpt|jd|jd|||jd|jd||} |jd| cxkr|jdkrnn| }|#t|j|j|||}|j!|} | dk(r t"|fcS||}}|j%|| \}}tj&|jdtj&|jdkrdnd} |j| |j| } } t)|j|j| dk(d\}}| d| z|z z }tj&|| z d |jd|jdz zkDrt+|jd z }ntj,|| |drtj.|jd}|| |d| z d z kr)d |j| z|jd| z zdz }nC| dk(rdnd }|tj&|z|j0z||j2zz}| |z}|jd|cxkr|jdksnt+|jd z }|j!|} | dk(rt"|fS||}}|j%|| \}}|jd|jdz |j4|zkDrO||}}t+|jd z }|j!|}|dk(rt"|fS|j%||\}}||c|_|_||c|_|_|j7\}}||fS)zkPerform one step in the algorithm. Implements Algorithm 4.1(k=1) or 4.2(k=2) in [APS1995] rrNrH rLFrrurP2r)rr7rrrorzrrrrrVrrrrrrrrr\rrr]frexprMr_MUr)rrorzrrrab_widthrnstepsc0ruixufurrfrsmmrlzfzstatusxns r iteratezTOMS748Solver.iterates 1hhuo!!vvtww7 2q"771: * Atvvax( 0FRH,12c6B' DGGAJ1(, TXXa["bJ771:/TWWQZ/Ay%dggtxxBGQBQw"A~%rrA((B/EAr% 0*FF488A;'"&&!*==q1 dhhsm2+DGGTXX58AXUL1 B N 66!a%=3$''!*twwqz"9: :DGG s"Azz!QSq1 hhtxx(+s8c!c'lR//dggcl*TWWQW-==CA #ax!RBrvvay.4994rDII~ECCAwwqzA2 2DGG s*A [[^ 7> !22$$Q+2 771: "TXX%8 8rrADGG s"AQBQw"A~%((B/EArRR__& rzr"rHc |j|||| ||j||||\} } | tk(r|j| St |j |j } |j d| cxkr|j dksnt|j dz } |j| } | dk(r|j| S|j| | \|_ |_ d\|_ |_ |xjdz c_ |j\} } | tk(r|j| S| t k(rCd}| r)||jdz|j fz}t#||j| t Sz)z3Solve f(x) = 0 given an interval containing a root.)rrMrbrerrrrP)NNz5Failed to converge after %d iterations, bracket is %s)rrrrrrrrrrrzrrrrrr[rW)rr?rrr;rrMrrbrerrrrfmtr=s r solvezTOMS748Solver.solves\ DtW41MZZ1a.  [ ??2& & DGGTXX &wwqzA* *DGG s"A [[^ 7??1% %..q"5$ 1JFB$r**"M1!4dgg >>C&s++r955r"N)T)r')r#r$r%r&rrrr!rrrrrrrrrrrrr'r"r rrbsZ C F F& !"-?90>0Ob#%u5t6r"rc Z|dkrtd|dd|tdz krtd|ddtdz ddtj|}|d kr td t j |std |t j |std |||k\rtd |d|d|d k\std|dt |ts|f}t|}t} | j|||||||||  } | \} } }}t|| | ||fdS)a Find a root using TOMS Algorithm 748 method. Implements the Algorithm 748 method of Alefeld, Potro and Shi to find a root of the function `f` on the interval ``[a , b]``, where ``f(a)`` and `f(b)` must have opposite signs. It uses a mixture of inverse cubic interpolation and "Newton-quadratic" steps. [APS1995]. Parameters ---------- f : function Python function returning a scalar. The function :math:`f` must be continuous, and :math:`f(a)` and :math:`f(b)` have opposite signs. a : scalar, lower boundary of the search interval b : scalar, upper boundary of the search interval args : tuple, optional containing extra arguments for the function `f`. `f` is called by ``f(x, *args)``. k : int, optional The number of Newton quadratic steps to perform each iteration. ``k>=1``. xtol : scalar, optional The computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The parameter must be positive. rtol : scalar, optional The computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. maxiter : int, optional If convergence is not achieved in `maxiter` iterations, an error is raised. Must be >= 0. full_output : bool, optional If `full_output` is False, the root is returned. If `full_output` is True, the return value is ``(x, r)``, where `x` is the root, and `r` is a `RootResults` object. disp : bool, optional If True, raise RuntimeError if the algorithm didn't converge. Otherwise, the convergence status is recorded in the `RootResults` return object. Returns ------- root : float Approximate root of `f` r : `RootResults` (present if ``full_output = True``) Object containing information about the convergence. In particular, ``r.converged`` is True if the routine converged. See Also -------- brentq, brenth, ridder, bisect, newton fsolve : find roots in N dimensions. elementwise.find_root : efficient elementwise 1-D root-finder Notes ----- `f` must be continuous. Algorithm 748 with ``k=2`` is asymptotically the most efficient algorithm known for finding roots of a four times continuously differentiable function. In contrast with Brent's algorithm, which may only decrease the length of the enclosing bracket on the last step, Algorithm 748 decreases it each iteration with the same asymptotic efficiency as it finds the root. For easy statement of efficiency indices, assume that `f` has 4 continuous deriviatives. For ``k=1``, the convergence order is at least 2.7, and with about asymptotically 2 function evaluations per iteration, the efficiency index is approximately 1.65. For ``k=2``, the order is about 4.6 with asymptotically 3 function evaluations per iteration, and the efficiency index 1.66. For higher values of `k`, the efficiency index approaches the kth root of ``(3k-2)``, hence ``k=1`` or ``k=2`` are usually appropriate. As mentioned in the parameter documentation, the computed root ``x0`` will satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the exact root. In equation form, this terminating condition is ``abs(x - x0) <= xtol + rtol * abs(x0)``. The default value ``xtol=2e-12`` may lead to surprising behavior if one expects `toms748` to always compute roots with relative error near machine precision. Care should be taken to select `xtol` for the use case at hand. Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the highest level of accuracy. Larger values of `xtol` may be useful for saving function evaluations when a root is at or near zero in applications where the tiny absolute differences available between floating point numbers near zero are not meaningful. References ---------- .. [APS1995] Alefeld, G. E. and Potra, F. A. and Shi, Yixun, *Algorithm 748: Enclosing Zeros of Continuous Functions*, ACM Trans. Math. Softw. Volume 221(1995) doi = {10.1145/210089.210111} Examples -------- >>> def f(x): ... return (x**3 - 1) # only one real root at x = 1 >>> from scipy import optimize >>> root, results = optimize.toms748(f, 0, 2, full_output=True) >>> root 1.0 >>> results converged: True flag: converged function_calls: 11 iterations: 5 root: 1.0 method: toms748 rrrCrDrrrrrrEza is not finite zb is not finite za and b are not an interval [z, ]z k too small (z < 1))r;rrrMrbrer) r9rrQrRr7rrrrArrr3)r?rrr;rrrMrbr,resolverr{r.rrrs r rr1s_t qy+D86:;; eai+D83uQwqkCDDnnW%G{9:: ;;q>+A3/00 ;;q>+A3/00Av82aSBCC 6=5122 dE "wA _F \\!Q4")6F*0'A~z4 ;NJ(M$ &&r") Nr'g`sbO>rNNgFT)NTT)0rX collectionsrrQr _optimizernumpyr7rrrrror__all__r _ESIGNERRr[ _EVALUEERR _ECALLBACKr CONVERGEDSIGNERRCONVERRVALUEERR INPROGRESSrrr1r3rAr rTr r r r rrrrrrrrrr'r"r r)s"%   HBHHUO               Iw 7 ,  <.@   $AC'*#']S@ ` FE54d/NE54n/bE54G/TE54}/L5&=A)- F((A  FL6L6^UEDR&r"