Reputation: 109
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))
Upvotes: 0
Views: 811
Reputation: 4547
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)
Upvotes: 1