Antwort

10

Mit scipy.optimize.fixed_point:

import scipy.optimize as optimize 

def func(x): 
    return -x**3+1 

# This finds the value of x such that func(x) = x, that is, where 
# -x**3 + 1 = x 
print(optimize.fixed_point(func,0)) 
# 0.682327803828 

Der Python-Code zu definieren fixed_point ist in scipy/optimize/minpack.py. Der genaue Standort hängt davon ab, wo scipy installiert ist. Sie können, dass

, indem Sie herausfinden,
In [63]: import scipy.optimize 

In [64]: scipy.optimize 
Out[64]: <module 'scipy.optimize' from '/usr/lib/python2.6/dist-packages/scipy/optimize/__init__.pyc'> 

Hier ist der Code in scipy 0.7.0:

def fixed_point(func, x0, args=(), xtol=1e-8, maxiter=500): 
    """Find the point where func(x) == x 

    Given a function of one or more variables and a starting point, find a 
    fixed-point of the function: i.e. where func(x)=x. 

    Uses Steffensen's Method using Aitken's Del^2 convergence acceleration. 
    See Burden, Faires, "Numerical Analysis", 5th edition, pg. 80 

    Example 
    ------- 
    >>> from numpy import sqrt, array 
    >>> from scipy.optimize import fixed_point 
    >>> def func(x, c1, c2): 
      return sqrt(c1/(x+c2)) 
    >>> c1 = array([10,12.]) 
    >>> c2 = array([3, 5.]) 
    >>> fixed_point(func, [1.2, 1.3], args=(c1,c2)) 
    array([ 1.4920333 , 1.37228132]) 

    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 

     anneal, brute -- global optimizers 

     fminbound, brent, golden, bracket -- local scalar minimizers 

     fsolve -- n-dimenstional root-finding 

     brentq, brenth, ridder, bisect, newton -- one-dimensional root-finding 

    """ 
    if not isscalar(x0): 
     x0 = asarray(x0) 
     p0 = x0 
     for iter in range(maxiter): 
      p1 = func(p0, *args) 
      p2 = func(p1, *args) 
      d = p2 - 2.0 * p1 + p0 
      p = where(d == 0, p2, p0 - (p1 - p0)*(p1-p0)/d) 
      relerr = where(p0 == 0, p, (p-p0)/p0) 
      if all(relerr < xtol): 
       return p 
      p0 = p 
    else: 
     p0 = x0 
     for iter in range(maxiter): 
      p1 = func(p0, *args) 
      p2 = func(p1, *args) 
      d = p2 - 2.0 * p1 + p0 
      if d == 0.0: 
       return p2 
      else: 
       p = p0 - (p1 - p0)*(p1-p0)/d 
      if p0 == 0: 
       relerr = p 
      else: 
       relerr = (p-p0)/p0 
      if relerr < xtol: 
       return p 
      p0 = p 
    raise RuntimeError, "Failed to converge after %d iterations, value is %s" % (maxiter,p) 
2

Versuchen Sie die SymPy Bibliothek. Hier ist ein relevant example:

>>> solve(x**3 + 2*x**2 + 4*x + 8, x) 
[-2*I, 2*I, -2] 

Ich bin nicht sicher, welcher Algorithmus SymPy verwendet die Gleichung zu lösen, though.

Verwandte Themen