cbitt
cbitt

Reputation: 11

Trouble with derivation- how to fix "TypeError: 'Add' object is not callable"

Programming in python with numpy and sympy, and my attempts to use derivatives in my code are falling flat. I frequently get either

"TypeError: 'Add' object is not callable"

and,

"ValueError: First variable cannot be a number: 1".

This is for a program meant to define Newton's Method for solving a root-finding problem. The sample equation I've used is 1/x+log(x)-2. I mention this because I've had a few issues with numpy's log function, as well. I think my problem has to do with the diff I'm using, as I'm not entirely certain how to use it to return an actual value, and the literature I've read on it isn't incredibly helpful.

def newton(p0, f, n, t):
    global p
    p = 0
    for i in range(1, n+1):
        p = p0 - f(p0)/diff(f(x),p0)
        if abs(p-p0) < t:
            return p
        p0 = p
        i = i + 1
    return f"The method failed after {n} iterations. The procedure was unsuccessful."

print(newton(p0=1, f=1/x+log(x)-2, n=10, t=5e-324))

I'm at least expecting a number, but I'm getting the errors I describe above.

Upvotes: 0

Views: 994

Answers (1)

heyu91
heyu91

Reputation: 1282

there are two problems in your code,

the first is the parameter f in your function should have a 'function' input, which means f=lambda x: 1/x+log(x)-2,

the second is p = p0 - f(p0)/diff(f(x),p0). If I understand correctly, you are expecting the diff function to perform as a derivation function, however, it's not. Maybe you can define your own derivation function:

def df(f, x):
    h = 1e-5
    return (f(x+h)-f(x))/h

then you can write p = p0 - f(p0)/df(f, p0)

so the whole code can be written as below:

def newton(p0, f, n, t):
    global p
    p = 0
    for i in range(1, n+1):
        def df(f, x):
            h = 1e-5
            return (f(x+h)-f(x))/h
        p = p0 - f(p0)/df(f, p0)
        if abs(p-p0) < t:
            return p
        p0 = p
        i = i + 1
    return f"The method failed after {n} iterations. The procedure was unsuccessful."

print(newton(p0=1, f=lambda x: 1/x+log(x)-2, n=10, t=5e-324))

Upvotes: 0

Related Questions