简体   繁体   中英

Output number of iterations for Newton Method using Scipy

I would like to know how I can output the number of iterations when finding the root using Newtons method. I am calculating the root automatically using Scipy, so I wanted to know if there is a way of knowing how many iterations it took:

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))

Spicy is a cool name for scipy. :)

Jokes aside, you simply need to include full_output=True in your call to newton (see the doc for more detail). Executing your code, I got this output by printing ans:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM