首页 > 解决方案 > 使用 Scipy 输出牛顿法的迭代次数

问题描述

我想知道在使用牛顿法找到根时如何输出迭代次数。我正在使用 Scipy 自动计算根,所以我想知道是否有办法知道它需要多少次迭代:

from spicy.optimize import newton
from math import *

f = lambda x : x**2 - sin(x)
ans = newton(f, 1, tol = 1.0E-8, maxiter = 100)
print(round(ans, 8))

标签: pythonscipynewtons-methodnumerical-analysis

解决方案


Spicy 是 scipy 的一个很酷的名字。:)

撇开玩笑不谈,你只需要full_output=True在你的调用中加入newton(有关更多详细信息,请参阅文档)。执行你的代码,我通过打印 ans 得到这个输出:

(0.8767262153950625,       converged: True
           flag: 'converged'
 function_calls: 7
     iterations: 6
           root: 0.8767262153950625)

推荐阅读