o
    lhX                     @   sL  d dl mZ d dlmZ ddlmZ G dd deZG dd dZG d	d
 d
ZG dd dZ	G dd dZ
G dd dZG dd dZdd ZG dd dZdd Zdd ZG dd dZG dd dZdd  ZG d!d" d"Zeee	e
eeeeeeeed#Zd0d(d)Zd1d+d,Zd-d. Zee_ee_ee_ed/krd d%lZe  d%S d%S )2    )print_function)copy   )xrangec                   @   s   e Zd Zdd ZdS )OptimizationMethodsc                 C   s   d S N ctxr   r   p/var/www/html/construction_image-detection-poc/venv/lib/python3.10/site-packages/mpmath/calculus/optimization.py__init__      zOptimizationMethods.__init__N)__name__
__module____qualname__r   r   r   r   r   r      s    r   c                   @   $   e Zd ZdZdZdd Zdd ZdS )Newtona]  
    1d-solver generating pairs of approximative root and error.

    Needs starting points x0 close to the root.

    Pro:

    * converges fast
    * sometimes more robust than secant with bad second starting point

    Contra:

    * converges slowly for multiple roots
    * needs first derivative
    * 2 function evaluations per iteration
       c                    s^   |_ t|dkr|d _ntdt|  _d|vr& fdd}n|d }|_d S )N   r   !expected 1 starting point, got %idfc                       j  | S r   r
   diffxfselfr   r   r   *      zNewton.__init__.<locals>.df)r
   lenx0
ValueErrorr   r   )r   r
   r   r!   kwargsr   r   r   r   r   "   s   
zNewton.__init__c                 c   sF    | j }| j}| j}	 |||||  }t|| }|}||fV  qr   )r   r   r!   abs)r   r   r   r!   x1errorr   r   r   __iter__0   s   
zNewton.__iter__Nr   r   r   __doc__maxstepsr   r'   r   r   r   r   r      s
    r   c                   @   r   )Secantz
    1d-solver generating pairs of approximative root and error.

    Needs starting points x0 and x1 close to the root.
    x1 defaults to x0 + 0.25.

    Pro:

    * converges fast

    Contra:

    * converges slowly for multiple roots
       c                 K   sf   || _ t|dkr|d | _| jd | _nt|dkr&|d | _|d | _ntdt| || _d S )Nr   r         ?r   z'expected 1 or 2 starting points, got %i)r
   r    r!   r%   r"   r   r   r
   r   r!   r#   r   r   r   r   K   s   


zSecant.__init__c                 c   sp    | j }| j}| j}||}	 ||}|| }|sd S || | }|s%d S ||||  }}|}|t|fV  qr   )r   r!   r%   r$   )r   r   r!   r%   f0f1lsr   r   r   r'   W   s"   zSecant.__iter__Nr(   r   r   r   r   r+   :   s
    r+   c                   @   r   )MNewtonat  
    1d-solver generating pairs of approximative root and error.

    Needs starting point x0 close to the root.
    Uses modified Newton's method that converges fast regardless of the
    multiplicity of the root.

    Pro:

    * converges fast for multiple roots

    Contra:

    * needs first and second derivative of f
    * 3 function evaluations per iteration
    r   c                       |_ t|dkstdt| |d __d|vr%fdd n|d   _d|vr8 fdd	}n|d }|_d S )
Nr   r   r   r   c                    r   r   r   r   r   r   r   r      r   zMNewton.__init__.<locals>.dfd2fc                    r   r   r   r   r   r   r   r   r5      r   zMNewton.__init__.<locals>.d2fr
   r    r"   r!   r   r   r5   r   r
   r   r!   r#   r5   r   r   r   r   r   r   {      

zMNewton.__init__c           
      c   st    | j }| j}| j}| j}	 |}||}|dkrd S ||}||}||||| |   8 }t|| }	||	fV  q)NTr   r!   r   r   r5   r$   
r   r   r   r   r5   prevxfxdfxd2fxr&   r   r   r   r'      s    
zMNewton.__iter__Nr(   r   r   r   r   r3   h   s
    r3   c                   @   r   )Halleya  
    1d-solver generating pairs of approximative root and error.

    Needs a starting point x0 close to the root.
    Uses Halley's method with cubic convergence rate.

    Pro:

    * converges even faster the Newton's method
    * useful when computing with *many* digits

    Contra:

    * needs first and second derivative of f
    * 3 function evaluations per iteration
    * converges slowly for multiple roots
    r   c                    r4   )
Nr   r   r   r   c                    r   r   r   r   r   r   r   r      r   zHalley.__init__.<locals>.dfr5   c                    r   r   r   r   r6   r   r   r5      r   zHalley.__init__.<locals>.d2fr7   r8   r   r9   r   r      r:   zHalley.__init__c           
      c   st    | j }| j}| j}| j}	 |}||}||}||}|d| | d|d  ||   8 }t|| }	||	fV  q)NTr   r;   r<   r   r   r   r'      s   $
zHalley.__iter__Nr(   r   r   r   r   rA      s
    rA   c                   @   r   )Mullera  
    1d-solver generating pairs of approximative root and error.

    Needs starting points x0, x1 and x2 close to the root.
    x1 defaults to x0 + 0.25; x2 to x1 + 0.25.
    Uses Muller's method that converges towards complex roots.

    Pro:

    * converges fast (somewhat faster than secant)
    * can find complex roots

    Contra:

    * converges slowly for multiple roots
    * may have complex values for real starting points and real roots

    http://en.wikipedia.org/wiki/Muller's_method
    r,   c                 K   s   || _ t|dkr|d | _| jd | _| jd | _n5t|dkr2|d | _|d | _| jd | _nt|dkrH|d | _|d | _|d | _ntdt| || _|d | _d S )Nr   r   r-   r      z*expected 1, 2 or 3 starting points, got %iverbose)r
   r    r!   r%   x2r"   r   rD   r.   r   r   r   r      s$   




zMuller.__init__c                 c   s2   | j }| j}| j}| j}||}||}||}	 || ||  }|| ||  }	|| ||  }
||	 |
 }|
| ||  }|dkrZ|dkrZ| jrXtd td|d|d| d S |}|}|}|}| j|d d| |  }t|| t|| kr| }|d| ||  8 }||}t|| }||fV  q)	NTr   zcanceled withzx0 =z, x1 =zand x2 =r      )	r   r!   r%   rE   rD   printr
   sqrtr$   )r   r   r!   r%   rE   fx0fx1fx2fx2x1fx2x0fx1x0wfx2x1x0rr&   r   r   r   r'      s>   
zMuller.__iter__Nr(   r   r   r   r   rB      s
    rB   c                   @   r   )	Bisectiona  
    1d-solver generating pairs of approximative root and error.

    Uses bisection method to find a root of f in [a, b].
    Might fail for multiple roots (needs sign change).

    Pro:

    * robust and reliable

    Contra:

    * converges slowly
    * needs sign change
    d   c                 K   s@   || _ t|dkrtdt| || _|d | _|d | _d S )Nr   %expected interval of 2 points, got %ir   r   )r
   r    r"   r   abr.   r   r   r   r   4  s   
zBisection.__init__c           	      c   s    | j }| j}| j}|| }||}	 | j|| d}||}|| }|dk r+|}n|dkr4|}|}n|| jjfV  |d }|| d t|fV  q)NTr   r   )r   rU   rV   r
   ldexpzeror$   )	r   r   rU   rV   r1   fbmfmsignr   r   r   r'   <  s&   zBisection.__iter__Nr(   r   r   r   r   rR   "  s
    rR   c                 C   sH   | dkr
dd }|S | dkrdd }|S | dkrdd }|S t d|  )	zE
    Return a function to calculate m for Illinois-like methods.
    illinoisc                 S   s   dS )N      ?r   fzrZ   r   r   r   getmU  r   z_getm.<locals>.getmpegasusc                 S   s   |||   S r   r   r`   r   r   r   rb   X     andersonc                 S   s   d| |  }|dkr|S dS )Nr   r   r_   r   )ra   rZ   r[   r   r   r   rb   [  s   zmethod '%s' not recognized)r"   )methodrb   r   r   r   _getmP  s   rg   c                   @   r   )Illinoisa  
    1d-solver generating pairs of approximative root and error.

    Uses Illinois method or similar to find a root of f in [a, b].
    Might fail for multiple roots (needs sign change).
    Combines bisect with secant (improved regula falsi).

    The only difference between the methods is the scaling factor m, which is
    used to ensure convergence (you can choose one using the 'method' keyword):

    Illinois method ('illinois'):
        m = 0.5

    Pegasus method ('pegasus'):
        m = fb/(fb + fz)

    Anderson-Bjoerk method ('anderson'):
        m = 1 - fz/fb if positive else 0.5

    Pro:

    * converges very fast

    Contra:

    * has problems with multiple roots
    * needs sign change
    r,   c                 K   s   || _ t|dkrtdt| |d | _|d | _|| _|d | _|d | _|dd| _	t
| j	| _| jrAtd	| j	  d S d S )
Nr   rT   r   r   tolrD   rf   r^   zusing %s method)r
   r    r"   rU   rV   r   ri   rD   getrf   rg   rb   rG   r.   r   r   r   r     s   



zIllinois.__init__c                 c   s    | j }| j}| j}| j}||}||}d }	 || }|dkr"d S || | }	|||	  }
||
}t|| jk rH| jrAtd|
 |
|fV  d S || dk rW|}|}|
}|}n| ||}|
}|}|| }| jrs|rs|dksstd| || d t|fV  q)NTr   zcanceled with z =r^   zm:r   )	rf   r   rU   rV   r$   ri   rD   rG   rb   )r   rf   r   rU   rV   farZ   r[   r1   r2   zra   r   r   r   r'     sB   


zIllinois.__iter__Nr(   r   r   r   r   rh   e  s
    rh   c                  O      d|d< t | i |S )z
    1d-solver generating pairs of approximative root and error.

    Uses Pegasus method to find a root of f in [a, b].
    Wrapper for illinois to use method='pegasus'.
    rc   rf   rh   argsr#   r   r   r   Pegasus     rq   c                  O   rm   )z
    1d-solver generating pairs of approximative root and error.

    Uses Anderson-Bjoerk method to find a root of f in [a, b].
    Wrapper for illinois to use method='pegasus'.
    re   rf   rn   ro   r   r   r   Anderson  rr   rs   c                   @   r   )Riddera  
    1d-solver generating pairs of approximative root and error.

    Ridders' method to find a root of f in [a, b].
    Is told to perform as well as Brent's method while being simpler.

    Pro:

    * very fast
    * simpler than Brent's method

    Contra:

    * two function evaluations per step
    * has problems with multiple roots
    * needs sign change

    http://en.wikipedia.org/wiki/Ridders'_method
    r,   c                 K   sT   || _ || _t|dkrtdt| |d | _|d | _|d | _|d | _d S )Nr   rT   r   r   rD   ri   )r
   r   r    r"   r%   rE   rD   ri   r.   r   r   r   r     s   


zRidder.__init__c                 c   s    | j }| j}| j}||}| j}||}	 d||  }||}||| |||  | ||d ||    }	||	}
t|
| jk rX| jrMt	d|
 |	t|| fV  d S |
| dk rc|	}|
}n|	}|
}t|| }|| d |fV  q)NTr_   r   zcanceled with f(x4) =r   )
r
   r   r%   rE   r]   rH   r$   ri   rD   rG   )r   r
   r   r%   rJ   rE   rK   x3fx3x4fx4r&   r   r   r   r'     s2   4
zRidder.__iter__Nr(   r   r   r   r   rt     s
    
rt   c                   @   r   )ANewtonz
    EXPERIMENTAL 1d-solver generating pairs of approximative root and error.

    Uses Newton's method modified to use Steffensens method when convergence is
    slow. (I.e. for multiple roots.)
    r   c                    sz   |_ t|dkstdt| |d __d|vr%fdd n|d   _ fdd}|_|d	 _d S )
Nr   r   r   r   c                    r   r   r   r   r   r   r   r     r   zANewton.__init__.<locals>.dfc                    s   | |  |   S r   r   r   )r   r   r   r   phi  s   zANewton.__init__.<locals>.phirD   )r
   r    r"   r!   r   r   rz   rD   )r   r
   r   r!   r#   rz   r   r9   r   r     s   
zANewton.__init__c           	      c   s    | j }| j}| j}| j}d}d}	 |}z||}W n ty,   | jr)td| Y d S w |}t|| }|rLt|| | dk rL| jrHtd |d7 }|dkr]t|}d}| jr]td ||fV  q)Nr   Tz$ZeroDivisionError: canceled with x =r   zconverging slowlyrC   zaccelerating convergence)	r!   r   r   rz   ZeroDivisionErrorrD   rG   r$   
steffensen)	r   r!   r   r   rz   r&   counterr=   	preverrorr   r   r   r'     s:   

zANewton.__iter__Nr(   r   r   r   r   ry     s
    ry   c                 C   s   |  |}| | j}|  || }t|}t|}|  ||}t|D ](}| }	|	|  |7  < |  ||	 | | }
t|D ]
}|
| |||f< qAq$|S )z
    Calculate the Jacobian matrix of a function at the point x0.

    This is the first derivative of a vectorial function:

        f : R^m -> R^n with m >= n
    )matrixrH   epsr    r   r   )r
   r   r   hr>   r[   nJjxjJjir   r   r   jacobianC  s   
r   c                   @   r   )MDNewtona  
    Find the root of a vector function numerically using Newton's method.

    f is a vector function representing a nonlinear equation system.

    x0 is the starting point close to the root.

    J is a function returning the Jacobian matrix for a point.

    Supports overdetermined systems.

    Use the 'norm' keyword to specify which norm to use. Defaults to max-norm.
    The function to calculate the Jacobian matrix can be given using the
    keyword 'J'. Otherwise it will be calculated numerically.

    Please note that this method converges only locally. Especially for high-
    dimensional systems it is not trivial to find a good starting point being
    close enough to the root.

    It is recommended to use a faster, low-precision solver from SciPy [1] or
    OpenOpt [2] to get an initial guess. Afterwards you can use this method for
    root-polishing to any precision.

    [1] http://scipy.org

    [2] http://openopt.org/Welcome
    
   c                    s|    | _ | _t|ttfr |}|jdksJ d|| _d|v r(|d | _n
 fdd}|| _|d | _	|d | _
d S )Nr   zneed a vectorr   c                     s     | S r   )r   r   r
   r   r   r   r     rd   zMDNewton.__init__.<locals>.JnormrD   )r
   r   
isinstancetuplelistr   colsr!   r   r   rD   )r   r
   r   r!   r#   r   r   r   r   r   x  s   

zMDNewton.__init__c                 c   s    | j }| j}| j}| j}| j|| }||}d}|s{| }|| }	| j|	|}
| jr;td t|	 td|
 | jj	}||
 }	 ||krR| jrOtd d}n | j|| }||}||k rg|}|}n|d }|||
  }qD||fV  |rd S d S )NFzJx:zs:Tzcanceled, won't get more excactr   )
r   r!   r   r   r
   r   lu_solverD   rG   one)r   r   r!   r   r   r>   fxnormcancelfxnJxr2   r1   r%   newnormr   r   r   r'     sF   

zMDNewton.__iter__Nr(   r   r   r   r   r   Z  s
    r   )newtonsecantmnewtonhalleymullerbisectr^   rc   re   ridderanewtonmdnewtonr   NFTc                    s   j }z>  j d7  _ |du r jd }|d||d< d|v r'|d |d< ||d< t|ttfr< fdd	|D }n |g}t|trYzt| }W n t	yX   t
d
w t|ttfrlt|fdd}	|	}z|| }
t|
tt jf}W n ty   ||d }
d}Y nw d|v r|d }|rt}d|vr fdd}||d< n|d }nt}||
dkr|r |W | _ S |d W | _ S | ||fi |}d|v r|d }n|j}d}|D ]'\}}|rtd| td| |d7 }||td|| k s||kr	 nq|st
dt|tt jfs|g}n|}|r=||| d |kr=t
d||| d |f |W | _ S | _ w )a4  
    Find an approximate solution to `f(x) = 0`, using *x0* as starting point or
    interval for *x*.

    Multidimensional overdetermined systems are supported.
    You can specify them using a function or a list of functions.

    Mathematically speaking, this function returns `x` such that
    `|f(x)|^2 \leq \mathrm{tol}` is true within the current working precision.
    If the computed value does not meet this criterion, an exception is raised.
    This exception can be disabled with *verify=False*.

    For interval arithmetic (``iv.findroot()``), please note that
    the returned interval ``x`` is not guaranteed to contain `f(x)=0`!
    It is only some `x` for which `|f(x)|^2 \leq \mathrm{tol}` certainly holds
    regardless of numerical error. This may be improved in the future.

    **Arguments**

    *f*
        one dimensional function
    *x0*
        starting point, several starting points or interval (depends on solver)
    *tol*
        the returned solution has an error smaller than this
    *verbose*
        print additional information for each iteration if true
    *verify*
        verify the solution and raise a ValueError if `|f(x)|^2 > \mathrm{tol}`
    *solver*
        a generator for *f* and *x0* returning approximative solution and error
    *maxsteps*
        after how many steps the solver will cancel
    *df*
        first derivative of *f* (used by some solvers)
    *d2f*
        second derivative of *f* (used by some solvers)
    *multidimensional*
        force multidimensional solving
    *J*
        Jacobian matrix of *f* (used by multidimensional solvers)
    *norm*
        used vector norm (used by multidimensional solvers)

    solver has to be callable with ``(f, x0, **kwargs)`` and return an generator
    yielding pairs of approximative solution and estimated error (which is
    expected to be positive).
    You can use the following string aliases:
    'secant', 'mnewton', 'halley', 'muller', 'illinois', 'pegasus', 'anderson',
    'ridder', 'anewton', 'bisect'

    See mpmath.calculus.optimization for their documentation.

    **Examples**

    The function :func:`~mpmath.findroot` locates a root of a given function using the
    secant method by default. A simple example use of the secant method is to
    compute `\pi` as the root of `\sin x` closest to `x_0 = 3`::

        >>> from mpmath import *
        >>> mp.dps = 30; mp.pretty = True
        >>> findroot(sin, 3)
        3.14159265358979323846264338328

    The secant method can be used to find complex roots of analytic functions,
    although it must in that case generally be given a nonreal starting value
    (or else it will never leave the real line)::

        >>> mp.dps = 15
        >>> findroot(lambda x: x**3 + 2*x + 1, j)
        (0.226698825758202 + 1.46771150871022j)

    A nice application is to compute nontrivial roots of the Riemann zeta
    function with many digits (good initial values are needed for convergence)::

        >>> mp.dps = 30
        >>> findroot(zeta, 0.5+14j)
        (0.5 + 14.1347251417346937904572519836j)

    The secant method can also be used as an optimization algorithm, by passing
    it a derivative of a function. The following example locates the positive
    minimum of the gamma function::

        >>> mp.dps = 20
        >>> findroot(lambda x: diff(gamma, x), 1)
        1.4616321449683623413

    Finally, a useful application is to compute inverse functions, such as the
    Lambert W function which is the inverse of `w e^w`, given the first
    term of the solution's asymptotic expansion as the initial value. In basic
    cases, this gives identical results to mpmath's built-in ``lambertw``
    function::

        >>> def lambert(x):
        ...     return findroot(lambda w: w*exp(w) - x, log(1+x))
        ...
        >>> mp.dps = 15
        >>> lambert(1); lambertw(1)
        0.567143290409784
        0.567143290409784
        >>> lambert(1000); lambert(1000)
        5.2496028524016
        5.2496028524016

    Multidimensional functions are also supported::

        >>> f = [lambda x1, x2: x1**2 + x2,
        ...      lambda x1, x2: 5*x1**2 - 3*x1 + 2*x2 - 3]
        >>> findroot(f, (0, 0))
        [-0.618033988749895]
        [-0.381966011250105]
        >>> findroot(f, (10, 10))
        [ 1.61803398874989]
        [-2.61803398874989]

    You can verify this by solving the system manually.

    Please note that the following (more general) syntax also works::

        >>> def f(x1, x2):
        ...     return x1**2 + x2, 5*x1**2 - 3*x1 + 2*x2 - 3
        ...
        >>> findroot(f, (0, 0))
        [-0.618033988749895]
        [-0.381966011250105]


    **Multiple roots**

    For multiple roots all methods of the Newtonian family (including secant)
    converge slowly. Consider this example::

        >>> f = lambda x: (x - 1)**99
        >>> findroot(f, 0.9, verify=False)
        0.918073542444929

    Even for a very close starting point the secant method converges very
    slowly. Use ``verbose=True`` to illustrate this.

    It is possible to modify Newton's method to make it converge regardless of
    the root's multiplicity::

        >>> findroot(f, -10, solver='mnewton')
        1.0

    This variant uses the first and second derivative of the function, which is
    not very efficient.

    Alternatively you can use an experimental Newtonian solver that keeps track
    of the speed of convergence and accelerates it using Steffensen's method if
    necessary::

        >>> findroot(f, -10, solver='anewton', verbose=True)
        x:     -9.88888888888888888889
        error: 0.111111111111111111111
        converging slowly
        x:     -9.77890011223344556678
        error: 0.10998877665544332211
        converging slowly
        x:     -9.67002233332199662166
        error: 0.108877778911448945119
        converging slowly
        accelerating convergence
        x:     -9.5622443299551077669
        error: 0.107778003366888854764
        converging slowly
        x:     0.99999999999999999214
        error: 10.562244329955107759
        x:     1.0
        error: 7.8598304758094664213e-18
        ZeroDivisionError: canceled with x = 1.0
        1.0

    **Complex roots**

    For complex roots it's recommended to use Muller's method as it converges
    even for real starting points very fast::

        >>> findroot(lambda x: x**4 + x + 1, (0, 1, 2), solver='muller')
        (0.727136084491197 + 0.934099289460529j)


    **Intersection methods**

    When you need to find a root in a known interval, it's highly recommended to
    use an intersection-based solver like ``'anderson'`` or ``'ridder'``.
    Usually they converge faster and more reliable. They have however problems
    with multiple roots and usually need a sign change to find a root::

        >>> findroot(lambda x: x**3, (-1, 1), solver='anderson')
        0.0

    Be careful with symmetric functions::

        >>> findroot(lambda x: x**2, (-1, 1), solver='anderson') #doctest:+ELLIPSIS
        Traceback (most recent call last):
          ...
        ZeroDivisionError

    It fails even for better starting points, because there is no sign change::

        >>> findroot(lambda x: x**2, (-1, .5), solver='anderson')
        Traceback (most recent call last):
          ...
        ValueError: Could not find root within given tolerance. (1.0 > 2.16840434497100886801e-19)
        Try another starting point or tweak arguments.

    r   Ni   rD   d1fr   ri   c                    s   g | ]}  |qS r   )convert).0r   r	   r   r   
<listcomp>  s    zfindroot.<locals>.<listcomp>zcould not recognize solverc                     s    fddD S )Nc                    s   g | ]}|  qS r   r   )r   fnrp   r   r   r     s    z)findroot.<locals>.tmp.<locals>.<listcomp>r   r   )f2r   r   tmp  s   zfindroot.<locals>.tmpr   Fmultidimensionalr   c                    s     | dS )Ninf)r   r   r	   r   r   <lambda>  s    zfindroot.<locals>.<lambda>r*   zx:    zerror:r   zZCould not find root using the given solver.
Try another starting point or tweak arguments.r   zdCould not find root within given tolerance. (%s > %s)
Try another starting point or tweak arguments.)precr   rj   r   r   r   r   str
str2solverKeyErrorr"   r   r   	TypeErrorr   r$   r*   rG   max)r
   r   r!   solverri   rD   verifyr#   r   r   r>   r   r   
iterationsr*   r   r   r&   xlr   )r
   r   r   findroot  s    R




!


"r   r   c                    st   |du r	 j d }|d< t|D ]&dt d }||v r$|| }n fdd}t|||k s7 S qS )a  
    Return the multiplicity of a given root of f.

    Internally, numerical derivatives are used. This might be inefficient for
    higher order derviatives. Due to this, ``multiplicity`` cancels after
    evaluating 10 derivatives by default. You can be specify the n-th derivative
    using the dnf keyword.

    >>> from mpmath import *
    >>> multiplicity(lambda x: sin(x) - 1, pi/2)
    2

    Ng?d0fdr   c                    s     | S r   )r   r   r
   r   r   r   r   r     s    zmultiplicity.<locals>.<lambda>)r   r   r   r$   )r
   r   rootri   r*   r#   dfstrr   r   r   r   multiplicity  s   

r   c                    s    fdd}|S )a	  
    linear convergent function -> quadratic convergent function

    Steffensen's method for quadratic convergence of a linear converging
    sequence.
    Don not use it for higher rates of convergence.
    It may even work for divergent sequences.

    Definition:
    F(x) = (x*f(f(x)) - f(x)**2) / (f(f(x)) - 2*f(x) + x)

    Example
    .......

    You can use Steffensen's method to accelerate a fixpoint iteration of linear
    (or less) convergence.

    x* is a fixpoint of the iteration x_{k+1} = phi(x_k) if x* = phi(x*). For
    phi(x) = x**2 there are two fixpoints: 0 and 1.

    Let's try Steffensen's method:

    >>> f = lambda x: x**2
    >>> from mpmath.calculus.optimization import steffensen
    >>> F = steffensen(f)
    >>> for x in [0.5, 0.9, 2.0]:
    ...     fx = Fx = x
    ...     for i in xrange(9):
    ...         try:
    ...             fx = f(fx)
    ...         except OverflowError:
    ...             pass
    ...         try:
    ...             Fx = F(Fx)
    ...         except ZeroDivisionError:
    ...             pass
    ...         print('%20g  %20g' % (fx, Fx))
                    0.25                  -0.5
                  0.0625                   0.1
              0.00390625            -0.0011236
             1.52588e-05           1.41691e-09
             2.32831e-10          -2.84465e-27
             5.42101e-20           2.30189e-80
             2.93874e-39          -1.2197e-239
             8.63617e-78                     0
            7.45834e-155                     0
                    0.81               1.02676
                  0.6561               1.00134
                0.430467                     1
                0.185302                     1
               0.0343368                     1
              0.00117902                     1
             1.39008e-06                     1
             1.93233e-12                     1
             3.73392e-24                     1
                       4                   1.6
                      16                1.2962
                     256               1.10194
                   65536               1.01659
             4.29497e+09               1.00053
             1.84467e+19                     1
             3.40282e+38                     1
             1.15792e+77                     1
            1.34078e+154                     1

    Unmodified, the iteration converges only towards 0. Modified it converges
    not only much faster, it converges even to the repelling fixpoint 1.
    c                    s0    | } |}| | |d  |d|  |   S )Nr   r   )r   r>   ffxr   r   r   FB  s    zsteffensen.<locals>.Fr   )r   r   r   r   r   r|     s   Er|   __main__)r   NFT)Nr   )
__future__r   r   libmp.backendr   objectr   r   r+   r3   rA   rB   rR   rg   rh   rq   rs   rt   ry   r   r   r   r   r   r|   r   doctesttestmodr   r   r   r   <module>   sF    +.76M.P
;>W
  
.K