Search code examples
pythonnumpynewtons-method

How can I adjust this Newton-Raphson for loop to include a range of values for my initial guess so that it prints the number of iterations for each?


I currently have this, I have tried to replace x by defining an 'np.arrange' to do this but keep getting an error that says "only integer scalar arrays can be converted to a scalar index", I think I may need to redefine my function but was hoping there was an easy way to slot in an array to give me a range of values for root and the number of iterations.

import math

#Define Newton-Raphson method as a function using a for loop
def nraphson(fn, dfn, x, tol, maxiter):
    for i in range(maxiter):
        xnew = x - fn(x)/dfn(x)
        if abs(xnew - x) < tol: break
        x = xnew
    return xnew, i

#Define f(x) and f'(x) to be used in Newton-Raphson function
y = lambda x: math.exp(x) - x**2
dy = lambda x: math.exp(x) - 2*x

#Run the Newton-Raphson method with initial x as -1 from estimate
x, n = nraphson(y, dy, -1, 0.0001, 100)
#Printing text allows us to see the value determined for the root
print("the root is %f at %d iterations." % (x,n))


Solution

  • As in this problem the number of iterations on each cell of input array may be different, then it may better to solve the problem by nested iterations. (nested for loops), I mean a loop iterating over each cell of input over nraphson function.