在SciPy中使用optimize.newton时如何手动处理发散失败?

How can I handle divergence failure manually when using optimize.newton in SciPy?

我正在使用 SciPy 的牛顿优化来求解方程,根据最初的猜测,有时解不会收敛并崩溃。

x = optimize.newton(fun,1/1000)

是否可以打印一条消息而不是 python 崩溃消息来表明收敛失败或使用不同的初始值重试优化?

来自documentation

disp: bool, optional

If True, raise a RuntimeError if the algorithm didn’t converge, with the error message containing the number of iterations and current function value. Otherwise the convergence status is recorded in a RootResults return object. Ignored if x0 is not scalar. Note: this has little to do with displaying, however the disp keyword cannot be renamed for backwards compatibility.

您应该将 disp 设置为 False,因为它默认启用:

optimize.newton(fun, 1/1000, disp=False)

您的结果和其他信息将在一个 RootResults 对象中。