有人告诉我,只要提供一阶导数,方法scipy.optimize.newton()就能解决复杂的功能.我不能使它工作. newton()的文档中没有提到任何复杂的函数.有人可以告诉我如何在SciPy中找到f(z)= 1 z ^ 2之类的函数的根吗?我需要解决更复杂的问题,但是一个简单的示例将极大地帮助我.
解决方法:
这是在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
请注意,牛顿不将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