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

4

我听说scipy.optimize.newton()方法可以解决复杂函数,只要提供第一阶导数。但我无法使其正常运行。newton()的文档没有提到复杂函数。有谁能告诉我如何在SciPy中找到像f(z) = 1 + z^2这样函数的根?我需要解决更加复杂的问题,但一个简单的例子将对我非常有帮助。

1个回答

6
这里是在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不能处理导数为零的点:

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

从我的经验来看,至少需要提供一阶导数,因为否则使用的割线法无法处理复值 x0,会通过某些错误消息表明无法检查复数的 x0 >= 0。在数学上是有效的,但在实现中可能存在错误... - Tobias Kienzler
1
可能是实现中的一个错误。请参见https://github.com/scipy/scipy/issues/10103。 - Warren Weckesser

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接