
    ^Mhb              
          d dl Z d dlmZ d dlZddlmZ ddlmZ d dlZ	dZ
dZd e	j        e          j        z  Zg d	Zd Zd
ZdZdZdZdZdZdZdZdZdZeeeeeeeeeeiZ G d de          Zd Zd Zd Z 	 	 	 d.dZ!d Z"deee
ddfd Z#deee
ddfd!Z$deee
ddfd"Z%deee
ddfd#Z&eefd$Z'd% Z(d& Z)	 	 d/d'Z*d( Z+d) Z,d* Z- G d+ d,          Z.ddeee
ddfd-Z/dS )0    N)
namedtuple   )_zeros)OptimizeResultd   g-=   )newtonbisectridderbrentqbrenthtoms748RootResults	convergedz
sign errorzconvergence errorzvalue errorzNo errorc                       e Zd ZdZd ZdS )r   a  Represents 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                     || _         || _        || _        |t          k    | _        |t
          v rt
          |         | _        n|| _        || _        d S N)root
iterationsfunction_calls_ECONVERGEDr   flag_mapflagmethod)selfr   r   r   r   r   s         X/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/scipy/optimize/_zeros_py.py__init__zRootResults.__init__7   sN    	$,,8 DIIDI    N)__name__
__module____qualname____doc__r!    r"   r    r   r   #   s-         &	 	 	 	 	r"   r   c                 H    | r|\  }}}}t          |||||          }||fS |S )Nr   r   r   r   r   r   full_outputrr   xfuncallsr   r   resultss           r    	results_cr1   C   sJ     ()%8Z1)3-5#'8 8 8 'zr"   c                 H    |\  }}}}| rt          |||||          }||fS |S )z:Select from a tuple of (root, funccalls, iterations, flag)r)   r*   r+   s           r    _results_selectr3   O   sJ    $%!AxT 1)3-5#'8 8 8 'zHr"   c                 $      fdd_         S )Nc                      | g|R  }xj         dz  c_         t          j        |          r*d|  d}t          |          }| |_        j         |_         ||S )Nr   zThe function value at x=z  is NaN; solver cannot continue.)_function_callsnpisnan
ValueError_x)r.   argsfxmsgerrff_raises        r    r@   z _wrap_nan_raise.<locals>.f_raise]   sy    Qq[4[[[1$8B<< 	-a - - -CS//CCF")"9CI	r"   r   )r6   )r?   r@   s   `@r    _wrap_nan_raiserA   [   s1    
 
 
 
 
 
  GNr"   r'   `sbO>2           FTc           
      @   |dk    rt          d|dd          t          j        |          }|dk     rt          d          t          j        |          dk    rt          | |||||||	          S t          j        |          d         dz  }|}d}|7d
}t          |          D ]"} | |g|R  }|dz  }|dk    rt          |	|||t          f|          c S  ||g|R  }|dz  }|dk    r[d}|
r|d|dz   |fz  z  }t          |          t          j        |t          d           t          |	|||dz   t          f|          c S ||z  }|r; ||g|R  }|dz  }d}||z  |z  dz  }t          j        |          dk     r|d|z
  z  }||z
  }t          j        ||||          rt          |	|||dz   t          f|          c S |}$nd}|||k    rt          d          |}nd}|d|z   z  }||dk    r|n| z  } | |g|R  }|dz  } | |g|R  }|dz  }t          |          t          |          k     r||||f\  }}}}t          |          D ]}||k    rp||k    rCd||z
   d}|
r|d|dz   |fz  z  }t          |          t          j        |t          d           ||z   dz  }t          |	|||dz   t          f|          c S t          |          t          |          k    r| |z  |z  |z   d||z  z
  z  }n| |z  |z  |z   d||z  z
  z  }t          j        ||||          rt          |	|||dz   t          f|          c S ||}}|} | |g|R  }|dz  }|
rd|dz   |fz  }t          |          t          |	|||dz   t          f|          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()

    r   ztol too small (g <= 0)r   maxiter must be greater than 0r'         ?Nr	   zDerivative was zero.z5 Failed to converge after %d iterations, value is %s.   
stacklevelhalleyrtolatolsecantzx1 and x0 must be differentg-C6?zTolerance of z	 reached.       @z4Failed to converge after %d iterations, value is %s.)r9   operatorindexr7   size_array_newtonasarrayranger3   r   RuntimeErrorwarningswarnRuntimeWarning	_ECONVERRabsisclose)funcx0fprimer;   tolmaxiterfprime2x1rO   r,   dispp0r/   r   itrfvalfderr=   newton_stepfder2adjpp1epsq0q1s                             r    r	   r	   m   sH   d axx838888999nW%%G{{9:::	wr{{QT2vtS'7(* * 	* 
B	c	!B	BH>> &	 &	C4?T???DMHqyy&"h[!A6K K K K K6"$t$$$DMHqyy, ,O7B-()C 's+++c>a@@@@&"ha!CVM M M M M+K -*T***A! "E)D0146#;;??39,K[ Az!Rd555 N&!XsQw!DfN N N N NBBM&	R >Rxx !>???BBCq3wB"''33t,BT"_t___AT"_t___Ar77SWWR^NBB>> 	 	CRxx88<"r'<<<C 0S"Qwm,- +3///M#~!DDDD"WO&!XsQw	!BFL L L L L r77SWW$$rB+BG<AArB+BG<Az!Rd555 N&!XsQw!DfN N N N NBBb4BMHH  E'13;HcAgy(I6RRRr"   c           
      L	   t          j        |d          }t          j        |t                    }	t          j        |	          }
|^t	          |          D ]K}t          j         | |g|R            }|                                s|                    t                    }	 nt          j         ||g|R            }|dk    }
|
                                s n||
         ||
         z  }|8t          j         ||g|R            }|dd|z  ||
         z  ||
         z  z
  z  }t          j        |t          j        ||t           j	                            }||
xx         |z  cc<   t          j
        |          |k    |	|
<   |	|
                                         s nMnt          j        t                    j        dz  }|d	|z   z  t          j        |dk    ||           z   }t          j         | |g|R            }t          j         | |g|R            }t          j        |t                    }t	          |          D ]}||k    }
|
                                s
||z   d
z  } n|||z
  z  |
         ||z
  |
         z  }t          j        |t          j        |||t           j	                            }||
         |z
  ||
<   |
 |z  }||z   |         d
z  ||<   ||
z  }t          j
        |          |k    |	|
<   |	|
                                         s n"||}}|}t          j         | |g|R            }|
 |	z  }|                                r|t||k    }||z  }|                                rTt          j        t!          ||         ||         z
  dz                      }t#          j        d|ddt&          d           n|                                rdnd}|dd}t#          j        |t&          d           nu|	                                ra|	                                rdnd}|dd|dd}|	                                rt+          |          t#          j        |t&          d           |rt-          dd          } |||	 |          }|S )z
    A vectorized version of Newton, Halley, and secant methods for arrays.

    Do not use this method directly. This method is called from `newton`
    when ``np.size(x0) > 1`` is ``True``. For docstring, see `newton`.
    T)copy)dtypeNr   rI         ?gQ?r   rR   rJ   zRMS of rF   z reached   rK   allsomesz derivatives were zeroz failed to converge after dz iterationsresult)r   r   zero_der)r7   array	ones_likeboolrX   rW   anyastyperesult_typefloat64r^   finfofloatrq   wheresqrtsumrZ   r[   r\   ry   rY   r   )r`   ra   rb   r;   rc   rd   re   r,   ro   failuresnz_der	iterationrj   rk   dprm   dxrp   rr   rs   activeactive_zero_derr~   
nonzero_dpzero_der_nz_dprmsall_or_somer=   r}   s                                r    rV   rV     s    	$A|AT***H\(##Fw 	 	I:dd1ntnnn--D88:: ;;t,,:ffQ....//DaiF::<< fV,B"
771#4t#4#4#4553rE&M!9DL!HHI
1BN1b"*$E$EFFFAfIIIOIII!vbzzS0HVF#''))  Xe__ $&!b&\BHQ!VR"555ZQ''ZR$((at,,,w 	- 	-IBhF::<< !VsNQ-(BGV+<<B
1BN1b"bj$I$IJJJA6
RAfI%g.O"$q&/!:S!@AofF!vbzzS0HVF#'')) rBBDDOdOOO,,BBw!H||~~ 9>'J&3N!!## WgN+a.??AEFF  77777TUVVVV $,<<>>=%%vK ::::CM#~!<<<<<	 9'||~~9ee6PPP'PPPP<<>> 	$s###c>a8888 +H&GHHF1xi**Hr"   c	                 V   t          |t                    s|f}t          j        |          }|dk    rt	          d|dd          |t
          k     rt	          d|ddt
          dd          t          |           } t          j        | ||||||||	  	        }	t          ||	d          S )	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.allclose(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.allclose(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.

    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

    r   xtol too small (rF   rG   rtol too small ( < )r
   )

isinstancetuplerS   rT   r9   _rtolrA   r   _bisectr1   
r?   abr;   xtolrO   rd   r,   rg   r-   s
             r    r
   r
     s    T dE"" wnW%%Gqyy:D::::;;;e||ADAAAuAAAABBBAq!QdGT;MMA[!X...r"   c	                 V   t          |t                    s|f}t          j        |          }|dk    rt	          d|dd          |t
          k     rt	          d|ddt
          dd          t          |           } t          j        | ||||||||	  	        }	t          ||	d          S )	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.allclose(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.allclose(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

    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.

    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
    r   r   rF   rG   r   r   r   r   )
r   r   rS   rT   r9   r   rA   r   _ridderr1   r   s
             r    r   r   E  s    l dE"" wnW%%Gqyy:D::::;;;e||ADAAAuAAAABBBAq!QdGT;MMA[!X...r"   c	                 V   t          |t                    s|f}t          j        |          }|dk    rt	          d|dd          |t
          k     rt	          d|ddt
          dd          t          |           } t          j        | ||||||||	  	        }	t          ||	d          S )	aa  
    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.allclose(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.allclose(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

    Notes
    -----
    `f` must be continuous.  f(a) and f(b) must have opposite signs.

    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
    r   r   rF   rG   r   r   r   r   )
r   r   rS   rT   r9   r   rA   r   _brentqr1   r   s
             r    r   r     s    ^ dE"" wnW%%Gqyy:D::::;;;e||ADAAAuAAAABBBAq!QdGT;MMA[!X...r"   c	                 V   t          |t                    s|f}t          j        |          }|dk    rt	          d|dd          |t
          k     rt	          d|ddt
          dd          t          |           } t          j        | ||||||||	  	        }	t          ||	d          S )	a_  Find 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.allclose(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.allclose(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

    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

    r   r   rF   rG   r   r   r   r   )
r   r   rS   rT   r9   r   rA   r   _brenthr1   r   s
             r    r   r   "  s    F dE"" wnW%%Gqyy:D::::;;;e||ADAAAuAAAABBBAq!QdGT;MMA[!X...r"   c                      t                     oSt          t          j                             o2t           fdt	           d d                   D                        }|S )Nc           	   3   ~   K   | ]7\  }}t          t          j        ||d z   d                             V  8dS )r   NrN   )r   r7   r_   ).0i_frP   fsrO   s      r    	<genexpr>z_notclose.<locals>.<genexpr>  sb       5 52 
2r!a%&&z4HHHII 5 5 5 5 5 5r"   r   )ry   r7   isfiniter   	enumerate)r   rO   rP   notclosefvalss   ``` r    	_notcloser     s     GG 5BKOO,, 5 5 5 5 5 5 5!*2crc7!3!35 5 5 5 5 5  r"   c                    | dd         \  }}|dd         \  }}||k    rt           j        S t          j        |          t          j        |          k    r| |z  |z  |z   d||z  z
  z  }n| |z  |z  |z   d||z  z
  z  }|S )z+Perform a secant step, taking a little careNrJ   r   )r7   nanr^   )xvalsfvalsra   rf   f0f1x2s          r    _secantr     s     2A2YFB2A2YFB	Rxxv	vbzzBF2JJcBhmb Qb[1cBhmb Qb[1Ir"   c                     |\  }}t          j        |          t          j        |          z  dk    rdnd}| |         ||         }}|||<   || |<   ||fS )z?Update a bracket given (c, fc), return the discarded endpoints.r   r   )r7   sign)	abfabcfcfafbidxrxrfxs	            r    _update_bracketr     s_    FBbgbkk)A--111Cgs3xBCHBsGs7Nr"   c                 V   |r|rt          j        |           } nt          j        |           ddd         } t          |           }||nt	          ||          }t          j        ||g          }|dd         |dddf<   t          d|          D ]F}t          j        ||dz
  d|dz
  f                   | |d         | d||z
           z
  z  ||d|f<   G|S t          j        |           } t          j        |          }t          j        |          }	|rdnd}
||
         |d<   t          dt          |                     D ]d}| ||t          |	          z   dz
           | dt          |	          dz
           z
  }t          j        |	          dd         |z  }	|	|
         ||<   e|S )a  Return 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].Nr   r   r   )r7   rW   r   lenminzerosrX   diff)r   r   NfullforwardMDDr   ddrowidx2Usedenoms               r    _compute_divided_differencesr     s      	*Ju%%EEHUOODDbD)EJJAAAq		Xq!f8111a4q! 	6 	6AAEFFAEM!233)eFQUFm35Bqrr1uII	JuE	%B
(5//C#qqG'NBqE1c%jj!!  aCHHq(()E-3s88a<-,@@gcll111o%G1Ir"   c                 @   t          j        |           } t          |           }t          j        ||g          }t          j        ||g          }|dd         |dddf<   |dd         |dddf<   t	          d|          D ]v}||d|dz
  f         ||dz
  |dz
  |dz
  f         z
  }| d||z
           | ||         z
  }| |d         |z
  |z  |z  ||d|f<   | d||z
           |z
  |z  |z  ||d|f<   wt          j        |dddf                   |d         z   S )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, fvalsNr   r   r   )r   r   )r7   rW   r   r   rX   r   )	r   r   r.   r   QDkalphadiffiks	            r    _interpolated_polyr     sY   
 JuEE

A
!QA
!QAAAAhAaaadGAAAhAaaadG1a[[ 8 8!""a!e)qQq1ua!e!344qQw%!*,!""IMV+e3!""a%&1q5&MA%/%7!""a%6!BF)qx''r"   c                 4    t          ||||g| |||gd          S )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   )r   r   r   r|   r   r   r   fds           r    _inverse_poly_zeror     s'     r2r2.Aq!a@@@r"   c                    | \  |\  }t          |g||gdd          \  }fd}dk    r	z  z
  }nt          j                  t          j                  z  dk    rn}t          |          D ]s}	| ||          d|z  z
  z
  z  z   z  z
  }
| d         |
cxk     r| d         k     s6n | d         |cxk     r| d         k     rn n|c S t	          |           dz  } n|
}t|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
    TFr   r   c                 ,    | z
  z  z   | z
  z  z   S r   r'   )r.   ABr   r   r   s    r    _Pz_newton_quadratic.<locals>._P  s#    QUaAE*R//r"   r   rJ   r   rR   )r   r7   r   rX   r   )r   r   r|   r   r   r   _r   r-   r   r1r   r   r   r   r   s              @@@@@r    _newton_quadraticr     sx    DAqFB*Aq!9r2rl37eE E EGAq!0 0 0 0 0 0 0 0 0 	AvvQJ'!**rwr{{*Q..QQAq 	 	ARRUUa!q1uqy1}"5566BqEB&&&&A&&&&qEA%%%%1%%%%%HHHGGcMAAHr"   c                   j    e Zd ZdZdZdZdZd Zd ZddZ	e
fd	Zd
 ZddZd Zd ZdeededfdZdS )TOMS748SolverzGSolve f(x, *args) == 0 using Algorithm748 of Alefeld, Potro & Shi.
    rw   r   r   c                 N   d | _         d | _        d| _        d| _        d| _        t
          j        t
          j        g| _        t
          j        t
          j        g| _        d | _	        d | _
        d | _        d | _        d| _        t          | _        t           | _        t$          | _        d S )Nr   rJ   F)r?   r;   r   r   r   r7   r   r   r   r|   r   eferg   _xtolr   r   rO   _iterrd   )r   s    r    r!   zTOMS748Solver.__init__(  s    	626"FBF#			r"   c                     || _         || _        || _        || _        t	          || j                  | _        | j        | j        k    r4d| j        z  }t          j	        |t          d           | j        | _        d S d S )Nztoms748: Overriding k: ->%drx   rK   )rg   r   rO   rd   max_K_MINr   _K_MAXrZ   r[   r\   )r   r   rO   rd   rg   r   r=   s          r    	configurezTOMS748Solver.configure;  sx    			Q$$6DK/$+=CM#~!<<<<[DFFF  r"   Tc                      | j         |g| j        R  }| xj        dz  c_        t          j        |          s|rt          d|dd| d          |S )z4Call the user-supplied function, update book-keepingr   Invalid function value: f(r?   ) ->  )r?   r;   r   r7   r   r9   )r   r.   errorr<   s       r    _callfzTOMS748Solver._callfH  st    TVA"	"""q {2 	K5 	KI!IIIBIIIJJJ	r"   c                 "    || j         | j        |fS )z/Package the result and statistics into a tuple.)r   r   )r   r.   r   s      r    
get_resultzTOMS748Solver.get_resultP  s    4&>>r"   c                 :    t          | j        | j        ||          S r   )r   r   r   )r   r   r   s      r    r   zTOMS748Solver._update_bracketT  s    tw!R888r"   r'   c                    d| _         d| _        || _        || _        ||g| j        dd<   t          j        |          rt          j        |          dk    rt          d| d          t          j        |          rt          j        |          dk    rt          d| d          | 	                    |          }t          j        |          rt          j        |          dk    rt          d|dd| d          |dk    r	t          |fS | 	                    |          }t          j        |          rt          j        |          dk    rt          d|dd| d          |dk    r	t          |fS t          j        |          t          j        |          z  dk    r t          d|d	d
|d	d|d	d
|d	d	          ||g| j        dd<   t          t          | j                  dz  fS )zPrepare for the iterations.r   NzInvalid x value: r   r   r?   r   z/f(a) and f(b) must have different signs, but f(r   z)=z, f(rR   )r   r   r?   r;   r   r7   r   imagr9   r   r   r   r   _EINPROGRESSr   )r   r?   r   r   r;   r   r   s          r    startzTOMS748Solver.startW  s.   	V
{1~~ 	7q5555666{1~~ 	7q5555666[[^^{2 	K"'"++"2"2I!IIIBIIIJJJ77>![[^^{2 	K"'"++"2"2I!IIIBIIIJJJ77>!72;;$q(( B"#AB B)+AB B34AB B:<AB B B C C C2hS\\C///r"   c                 >   | j         dd         \  }}t          j        ||| j        | j                  rt
          t          | j                   dz  fS | j        | j        k    rt          t          | j                   dz  fS t          t          | j                   dz  fS )zDetermine the current status.NrJ   rN   rR   )r   r7   r_   rO   r   r   r   r   rd   r]   r  )r   r   r   s      r    
get_statuszTOMS748Solver.get_statusv  s    wrr{1:a;;; 	3DGs 222?dl**c$'llS000S\\C///r"   c                 ^   | xj         dz  c_         t          j        t                    j        }| j        | j        | j        | j        f\  }}}}| j	        d         | j	        d         z
  }d}t          d| j        dz             D ]}t          | j        ||gz   dd|z            rjt          | j	        d         | j	        d         ||| j        d         | j        d         ||          }	| j	        d         |	cxk     r| j	        d         k     rn n|	}|t          | j	        | j        |||          }|                     |          }
|
dk    rt"          |fc S ||}}|                     ||
          \  }}t          j        | j        d                   t          j        | j        d                   k     rdnd}| j	        |         | j        |         }}t)          | j	        | j        |dk    d          \  }}|d|z  |z  z
  }t          j        ||z
            d	| j	        d         | j	        d         z
  z  k    rt+          | j	                  d
z  }nt          j        |||d          rt          j        | j                  d         }||         |d|z
           dz
  k     r%d| j	        |         z  | j	        d|z
           z   dz  }n9|dk    rdnd}|t          j        |          z  | j        z  || j        z  z   }||z   }| j	        d         |cxk     r| j	        d         k     sn t+          | j	                  d
z  }|                     |          }
|
dk    r	t"          |fS ||}}|                     ||
          \  }}| j	        d         | j	        d         z
  | j        |z  k    rX||}}t+          | j	                  d
z  }|                     |          }|dk    r	t"          |fS |                     ||          \  }}||c| _        | _        ||c| _        | _        |                                 \  }}||fS )zkPerform one step in the algorithm.

        Implements Algorithm 4.1(k=1) or 4.2(k=2) in [APS1995]
        r   r   NrJ       rN   Fr   rw   rR   rC      r   )r   r7   r   r   rq   r|   r   r   r   r   rX   r   r   r   r   r   r   r   r   r^   r   r   r_   frexprO   r   _MUr  )r   rq   r|   r   r   r   ab_widthr   nstepsc0r   uixufur   r   frsmmrn   zfzstatusxns                          r    iteratezTOMS748Solver.iterate  s3   
 	1huoo!vtw72q"71:
*Atvax(( 	0 	0F RH,12c6BBB '
DGAJ1(,TXa["bJ J71:////TWQZ/////Ay%dgtxBGGQBQww"A~%%% rrA((B//EArr F48A;''"&!*=*===qq1dhsm2+DGTX58AXUL L L1B
N6!a%==3$'!*twqz"9:::DGs"AAz!QSq111 +
 htx((+s8c!c'lR///dgcl*TWQW-==CAA  #axx!!RBrvayy.494rDI~ECCAwqzA2222
2222DGs*A[[^^77>!22$$Q++2 71:
"TX%888rrADGs"AQBQww"A~%((B//EAr RR__&&
rzr"   rJ   c
                 H   |                      ||||	|           |                     ||||          \  }
}|
t          k    r|                     |          S t	          | j        | j                  }| j        d         |cxk     r| j        d         k     sn t          | j                  dz  }|                     |          }|dk    r|                     |          S | 	                    ||          \  | _
        | _        d\  | _        | _        | xj        dz  c_        	 |                                 \  }
}|
t          k    r|                     |          S |
t           k    rBd}|	r#|| j        dz   | j        fz  }t#          |          |                     |t                     S )z3Solve f(x) = 0 given an interval containing a root.)r   rO   rd   rg   r   r   r   rR   )NNTz5Failed to converge after %d iterations, bracket is %s)r   r  r   r   r   r   r   r   r   r   r|   r   r   r   r   r  r]   rY   )r   r?   r   r   r;   r   rO   r   rd   rg   r  r  r   r   fmtr=   s                   r    solvezTOMS748Solver.solve  s    	DtW41MMMZZ1a..
[  ??2&&& DGTX&&wqzA****
****DGs"A[[^^77??1%%%..q"55$1		6JFB$$r***""M ,1!4dg >>C&s+++r9555		6r"   N)T)r'   )r#   r$   r%   r&   r	  r   r   r!   r   r   r   r   r   r  r  r  r   r   r   r  r'   r"   r    r   r   !  s         
CFF  &! ! !    "- ? ? ? ?9 9 90 0 0 0>0 0 0O O Ob #%u5t6 6 6 6 6 6r"   r   c
                    |dk    rt          d|dd          |t          dz  k     r t          d|ddt          dz  dd          t          j        |          }|d	k     rt          d
          t	          j        |          st          d|           t	          j        |          st          d|           ||k    rt          d| d| d          |d	k    st          d| d          t          |t                    s|f}t          |           } t                      }
|

                    | ||||||||		  	        }|\  }}}}t          |||||fd          S )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.allclose(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.allclose(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.

    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.

    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
    r   r   rF   rG   r   r   r   r   r   rH   za is not finite zb is not finite za and b are not an interval [z, ]zk too small (z < 1))r;   r   r   rO   rd   rg   r   )r9   r   rS   rT   r7   r   r   r   rA   r   r  r3   )r?   r   r   r;   r   r   rO   rd   r,   rg   solverr}   r.   r   r   r   s                   r    r   r     s   V qyy:D::::;;;eaiCDCCCuQwCCCCDDDnW%%G{{9:::;q>> 1/A//000;q>> 1/A//000AvvBBBaBBBCCC661111222dE"" wA__F\\!Q4")  6 6F*0'A~z4;NJ(M$& & &r"   )	Nr'   rB   rC   NNrD   FT)NTT)0rZ   collectionsr   rS    r   	_optimizer   numpyr7   r   r   r   r   rq   r   __all__r   	_ESIGNERRr]   
_EVALUEERR
_ECALLBACKr  	CONVERGEDSIGNERRCONVERRVALUEERR
INPROGRESSr   r   r1   r3   rA   r	   rV   r
   r   r   r   r   r   r   r   r   r   r   r   r   r'   r"   r    <module>r*     s    " " " " " "        % % % % % %     		HBHUOO   		

	


 Iw	7,
<    .   @	 	 		 	 	  $ AC'*#'\S \S \S \S~` ` `F E54S/ S/ S/ S/l E54_/ _/ _/ _/D E54x/ x/ x/ x/v E54l/ l/ l/ l/j 5      &   =A)-       F( ( ((A A A     FL6 L6 L6 L6 L6 L6 L6 L6^ UEDC& C& C& C& C& C&r"   