L iOdZddlZddlmZddlmZdgZgdZ Gdd Z dd Z d Z d Z d ZdZdZdZdZdZy)z Unified interfaces to root finding algorithms for real or complex scalar functions. Functions --------- - root : find a root of a scalar function. N) _zeros_pyapprox_derivative root_scalar)bisectbrentqbrenthriddertoms748newtonsecanthalleyc.eZdZdZdZdZdZdZdZy) MemoizeDeraDecorator that caches the value and derivative(s) of function each time it is called. This is a simplistic memoizer that calls and caches a single value of ``f(x, *args)``. It assumes that `args` does not change between invocations. It supports the use case of a root-finder where `args` is fixed, `x` changes, and only rarely, if at all, does x assume the same value more than once.c<||_d|_d|_d|_yNr)funvalsxn_calls)selfrs a/mnt/ssd/data/python-lab/Trading/venv/lib/python3.12/site-packages/scipy/optimize/_root_scalar.py__init__zMemoizeDer.__init__s  c|j||jk7r9|j|g|}||_|xjdz c_|dd|_|jdS)z,Calculate f or use cached value if availableNrr)rrrr)rrargsfgs r__call__zMemoizeDer.__call__$s[ 99 TVV !#d#BDF LLA L1DIyy|rch|j||jk7r ||g||jdS)z/Calculate f' or use a cached value if availablerrrrrrs rfprimezMemoizeDer.fprime./ 99 TVV NTNyy|rch|j||jk7r ||g||jdS)z0Calculate f'' or use a cached value if availabler!r"s rfprime2zMemoizeDer.fprime24r$rc|jS)N)r)rs rncallszMemoizeDer.ncalls:s ||rN) __name__ __module__ __qualname____doc__rrr#r'r)rrrrs    rrc @t|ts|f}| i} d} |>t|s3t|r&t d} j }j }nd}|2t|s't|rt d} j }nd}i} dD]#}tj|}||| |<%| r| j| | jdd|s|d}n||r|rd}n d}n|d }nd}|s td |j}ddd } tt|j||}|d vrPt|ttzt j"zstd||dd\}} |||fd|i| \}}n|dvr;|td|d| vr| j1d| d<||f|dd|d| \}}n|dvrA|td||sfd}d| vr| j1d| d<||f||dd| \}}nl|dvrZ|td||std||std|d| vr| j1d| d<||f|||d| \}}ntd || rj2}||_|S#t$r}td ||d}~wwxYw#t$r]}t%|drFtj&|j(t j*|j,t/||}nYd}~d}~wwxYw)a Find a root of a scalar function. Parameters ---------- f : callable A function to find a root of. Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where ``my_args`` and ``my_kwargs`` are required positional and keyword arguments. Rather than passing ``f0`` as the callable, wrap it to accept only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been gathered before invoking this function. args : tuple, optional Extra arguments passed to the objective function and its derivative(s). method : str, optional Type of solver. Should be one of - 'bisect' :ref:`(see here) ` - 'brentq' :ref:`(see here) ` - 'brenth' :ref:`(see here) ` - 'ridder' :ref:`(see here) ` - 'toms748' :ref:`(see here) ` - 'newton' :ref:`(see here) ` - 'secant' :ref:`(see here) ` - 'halley' :ref:`(see here) ` bracket: A sequence of 2 floats, optional An interval bracketing a root. ``f(x, *args)`` must have different signs at the two endpoints. x0 : float, optional Initial guess. x1 : float, optional A second guess. fprime : bool or callable, optional If `fprime` is a boolean and is True, `f` is assumed to return the value of the objective function and of the derivative. `fprime` can also be a callable returning the derivative of `f`. In this case, it must accept the same arguments as `f`. fprime2 : bool or callable, optional If `fprime2` is a boolean and is True, `f` is assumed to return the value of the objective function and of the first and second derivatives. `fprime2` can also be a callable returning the second derivative of `f`. In this case, it must accept the same arguments as `f`. xtol : float, optional Tolerance (absolute) for termination. rtol : float, optional Tolerance (relative) for termination. maxiter : int, optional Maximum number of iterations. options : dict, optional A dictionary of solver options. E.g., ``k``, see :obj:`show_options()` for details. Returns ------- sol : RootResults The solution represented as a ``RootResults`` object. Important attributes are: ``root`` the solution , ``converged`` a boolean flag indicating if the algorithm exited successfully and ``flag`` which describes the cause of the termination. See `RootResults` for a description of other attributes. See also -------- show_options : Additional options accepted by the solvers root : Find a root of a vector function. Notes ----- This section describes the available solvers that can be selected by the 'method' parameter. The default is to use the best method available for the situation presented. If a bracket is provided, it may use one of the bracketing methods. If a derivative and an initial value are specified, it may select one of the derivative-based methods. If no method is judged applicable, it will raise an Exception. Arguments for each method are as follows (x=required, o=optional). +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | method | f | args | bracket | x0 | x1 | fprime | fprime2 | xtol | rtol | maxiter | options | +===============================================+===+======+=========+====+====+========+=========+======+======+=========+=========+ | :ref:`bisect ` | x | o | x | | | | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`brentq ` | x | o | x | | | | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`brenth ` | x | o | x | | | | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`ridder ` | x | o | x | | | | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`toms748 ` | x | o | x | | | | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`secant ` | x | o | | x | o | | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`newton ` | x | o | | x | | o | | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ | :ref:`halley ` | x | o | | x | | x | x | o | o | o | o | +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+ Examples -------- Find the root of a simple cubic >>> from scipy import optimize >>> def f(x): ... return (x**3 - 1) # only one real root at x = 1 >>> def fprime(x): ... return 3*x**2 The `brentq` method takes as input a bracket >>> sol = optimize.root_scalar(f, bracket=[0, 3], method='brentq') >>> sol.root, sol.iterations, sol.function_calls (1.0, 10, 11) The `newton` method takes as input a single point and uses the derivative(s). >>> sol = optimize.root_scalar(f, x0=0.2, fprime=fprime, method='newton') >>> sol.root, sol.iterations, sol.function_calls (1.0, 11, 22) The function can provide the value and derivative(s) in a single call. >>> def f_p_pp(x): ... return (x**3 - 1), 3*x**2, 6*x >>> sol = optimize.root_scalar( ... f_p_pp, x0=0.2, fprime=True, method='newton' ... ) >>> sol.root, sol.iterations, sol.function_calls (1.0, 11, 11) >>> sol = optimize.root_scalar( ... f_p_pp, x0=0.2, fprime=True, fprime2=True, method='halley' ... ) >>> sol.root, sol.iterations, sol.function_calls (1.0, 7, 8) NFT)xtolrtolmaxiter) full_outputdispr rr rzIUnable to select a solver as neither bracket nor starting point provided.)rrzUnknown solver )rr r r r zBracket needed for r&r_x)root iterationsfunction_callsflagmethod)rzx0 must not be None for r0tol)rr#r'x1)r c2fd}t||d|dS)Nc|dg|Srr.)rrfs r f_wrappedz.root_scalar..fprime..f_wrappedAsQqT>D>)rz2-point)r:rrr)rrr@r?s rr#zroot_scalar..fprime9s*(AidSTUVVr)rr#r')rzfprime must be specified for zfprime2 must be specified for ) isinstancetuplecallableboolrr'r#localsgetupdate ValueErrorlowergetattroptzerosAttributeErrorlistnpndarrayhasattr RootResultsr5nan_function_callsstrpoprr8)r?rr:bracketr#r'x0r<r0r1r2options is_memoizedkwargskvmethmap2underlyingmethodceabrsolrs` rrr>sr dE "wK8G#4 =1 AKiiGXXFG (6"2 <1 AKXXFFF ( HLLO =F1I  g MMdM/   F ^%F%F!! 89 9 <<>D (H=N:(N$6$6tT$BC BB'4%<"**#<=26(;< <r{1 Q1:4:6:FAs   :7x@A A V "JJv.F5MB*T$*"(*3   :7x@A A W V "JJv.F5MB#T&$#!#3   :7x@A Ar|so#' /5''T26%) .2 ^B  , * , 0 4 > , r