在SciPy / NumPy中查找复杂函数的零

时间:2014-06-25 17:13:22

标签: python numpy scipy

我被告知,只要提供了一阶导数,方法scipy.optimize.newton()将解决复杂函数。我不能让它发挥作用。 newton()的文档没有提到复杂的函数。有人能告诉我如何在SciPy中找到像f(z)= 1 + z ^ 2这样的函数的根?我需要解决一些更为复杂的问题,但一个简单的例子对我有很大帮助。

1 个答案:

答案 0 :(得分:4)

以下是在IPython会话中使用newton复杂功能的示例:

In [1]: def func(z):
   ...:     return 1 + z*z
   ...: 

In [2]: def deriv(z):
   ...:     return 2*z
   ...: 

In [3]: from scipy.optimize import newton

In [4]: newton(func, x0=1+1j, fprime=deriv, tol=1e-12)
Out[4]: 1j

In [5]: newton(func, x0=-2j, fprime=deriv, tol=1e-12)
Out[5]: -1j

请注意,newton不会将x0作为导数为零的点处理:

In [6]: newton(func, x0=0, fprime=deriv, tol=1e-12)
/Users/warren/local_scipy/lib/python2.7/site-packages/scipy/optimize/zeros.py:119: RuntimeWarning: derivative was zero.
  warnings.warn(msg, RuntimeWarning)
Out[6]: 0.0

此外,如果函数返回实参数的实数值,请务必传入x0的复数值。否则该功能卡在实轴上:

In [21]: newton(func, x0=0.5, fprime=deriv, tol=1e-12)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-21-2feb08057c57> in <module>()
----> 1 newton(func, x0=0.5, fprime=deriv, tol=1e-12)

/Users/warren/local_scipy/lib/python2.7/site-packages/scipy/optimize/zeros.pyc in newton(func, x0, fprime, args, tol, maxiter, fprime2)
    159             q1 = func(*((p1,) + args))
    160     msg = "Failed to converge after %d iterations, value is %s" % (maxiter, p)
--> 161     raise RuntimeError(msg)
    162 
    163 

RuntimeError: Failed to converge after 50 iterations, value is -0.870752774435

增加maxiter不会有帮助:

In [22]: newton(func, x0=0.5, fprime=deriv, tol=1e-12, maxiter=1000)
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
[...]
RuntimeError: Failed to converge after 1000 iterations, value is -0.0895687261655