[英]Finding zeros of a complex function in SciPy/NumPy
I've been told that the method scipy.optimize.newton() will solve complex functions so long as the first derivative is provided. 我被告知,只要提供了一阶导数,方法scipy.optimize.newton()将解决复杂函数。 I can't make it work.
我不能让它发挥作用。 The documentation for newton() mentions nothing of complex functions.
newton()的文档没有提到复杂的函数。 Could someone show me how one would find the roots of a function like f(z) = 1 + z^2 in SciPy?
有人能告诉我如何在SciPy中找到像f(z)= 1 + z ^ 2这样的函数的根? I need to solve something much more complex, but a simple example will help me immensely.
我需要解决一些更复杂的问题,但一个简单的例子将对我有所帮助。
Here's an example of the use of newton
with a complex function, in an IPython session: 以下是在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
Note that newton
doesn't handle x0
being a point where the derivative is zero: 请注意,
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
Also, if your function returns real values for real arguments, be sure to pass in a complex value for x0
. 此外,如果函数返回实参数的实数值,请务必传入
x0
的复数值。 Otherwise the function is stuck on the real axis: 否则该功能卡在实轴上:
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
Increasing maxiter
won't help: 增加
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.