0

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

martineau
  • 119,623
  • 25
  • 170
  • 301
Ryan McAree
  • 37
  • 1
  • 8
  • 1
    If you're using NumPy, you should be using it _instead_ of `math`. Replace `math.exp(x)` with `np.exp(x)`, and you should be good – ForceBru Oct 14 '21 at 17:16

1 Answers1

1

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.

Seyfi
  • 1,832
  • 1
  • 20
  • 35