Ryan Tan
Ryan Tan

Reputation: 1

TypeError in Newton-Raphson in Python

I am a newbie at Python. I am attempting the Newton-Raphson root-finding method. In line 4, I get the error "Exception has occurred: TypeError 'numpy.float64' object is not callable". Would appreciate if someone could enlighten me on what the issue is. Thanks.

import numpy as np

def newton(f, df, x, tol=1e-8, max_it=20, it_count = 0):
    x -= f(x)/df(x)
    it_count += 1

    if it_count > max_it:
        raise ValueError("Maximum number of iterations has been exceeded")
    elif abs(f(x)) <= tol:
        return x
    else:
        x = newton(f, df, x)

def f(x):
    return np.tan(x) - 2*x

def df(x):
    d = 0.0000001
    return (f(x+d)-f(x-d))/(2*d)

print(newton(f(1.2), df(1.2), 1.2))

Upvotes: 0

Views: 272

Answers (3)

saki
saki

Reputation: 166

# Defining Function
def f(x):
    return x**3 - 5*x - 9

# Defining derivative of function
def g(x):
    return 3*x**2 - 5

# Implementing Newton Raphson Method

def newtonRaphson(x0,e,N):
    print('\n\n*** NEWTON RAPHSON METHOD IMPLEMENTATION ***')
    step = 1
    flag = 1
    condition = True
    while condition:
        if g(x0) == 0.0:
            print('Divide by zero error!')
            break

        x1 = x0 - f(x0)/g(x0)
        print('Iteration-%d, x1 = %0.6f and f(x1) = %0.6f' % (step, x1, f(x1)))
        x0 = x1
        step = step + 1

        if step > N:
            flag = 0
            break

        condition = abs(f(x1)) > e

    if flag==1:
        print('\nRequired root is: %0.8f' % x1)
    else:
        print('\nNot Convergent.')


# Input Section
x0 = input('Enter Guess: ')
e = input('Tolerable Error: ')
N = input('Maximum Step: ')

# Converting x0 and e to float
x0 = float(x0)
e = float(e)

# Converting N to integer
N = int(N)


#Note: You can combine above three section like this
# x0 = float(input('Enter Guess: '))
# e = float(input('Tolerable Error: '))
# N = int(input('Maximum Step: '))

# Starting Newton Raphson Method
newtonRaphson(x0,e,N)

View Code & Output Here

Also check codesansar.com/numerical-methods/. This site has large collection of algorithms, pseudocodes, and programs using C, C++, Python & MATLAB for Numerical Methods.

Upvotes: 0

Chris
Chris

Reputation: 999

In the last line you are handing the function and the gradient evaluated at a certain point instead of the functions themselves. You could try to alter your last line to the following:

print(newton(f, df, 1.2))

As pointed out by Belliger, you should also hand over the iteration count in the recursive function call. Besides, you should return the value in the recursion. Here is a working version of the code:

import numpy as np

def newton(f, df, x, tol=1e-8, max_it=20, it_count = 0):
    x -= f(x)/df(x)
    it_count += 1

    if it_count > max_it:
        raise ValueError("Maximum number of iterations has been exceeded")
    elif abs(f(x)) <= tol:
        return x
    else:
        x = newton(f, df, x, it_count=it_count)
        return x

def f(x):
    return np.tan(x) - 2*x

def df(x):
    d = 0.0000001
    return (f(x+d)-f(x-d))/(2*d)

print(newton(f, df, 1.2))

Upvotes: 2

Belliger
Belliger

Reputation: 76

Other answers have answered your question, but just another thing I've noticed, you'll need to pass the it_count when you apply your recursive call, e.g.

else:
   x = newton(f, df, x, it_count=it_count)

Upvotes: 0

Related Questions