0

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.

Duck Dodgers
  • 3,409
  • 8
  • 29
  • 43
cbitt
  • 11
  • 1
  • 3

1 Answers1

0

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))
heyu91
  • 1,174
  • 11
  • 18
  • My Terminal really doesn't like something about df(f,p0)– as soon as I use that in the code and hit "enter" in Terminal, the application doesn't show anything at all. – cbitt Feb 13 '19 at 16:35
  • I don't know what happened at your terminal. I tried in Jupyter Notebook, it works fine. – heyu91 Feb 14 '19 at 08:51