Pidge G. Pidge G. - 1 year ago 142
Python Question

Newtons Method of a User-defined Function

I am trying to find the roots of an equation using Newton's method. This is probably a very obvious mistake, but I keep getting an error that states: "TypeError: cannot determine truth value of Relational". Is there something I forgot to import/include? Sorry, I am very new to python.

import sympy

from sympy import *
x, y, z = symbols('x y z')

def newton(f, n, eps):
y = f(n)
delta = diff(eps, x)
while abs(y) > eps:
dy = (f(n + delta) - y) / delta
n = n - y/dy
y = f(n)
return n

def f(n):
return 5 * n + 10

eps = input("input function:")

print(newton(f, 0, eps))

Answer Source

Your code is not implementing Newton's method. You want to estimate the tangent line at an initial guess, intercept it with y=0 to get a new guess and keep doing that until the function at the guess value is close enough to 0. See the code below.

def newton(f, x, eps=1e-50):
    y = f(x)
    delta = 1e-10
    while abs(y) > eps:
        dy = (f(x+delta) - y) / delta
        x = x - y/dy
        y = f(x)
    return x

def f(x):
    return 5 * x + 10

newton(f, 0) # outputs -2.0

User-supplied functions via text are not easily doable. What we are usually doing is providing a numerical implementation of the function as above.

If you want to operate on the symbolical level you need to parse the string and construct a suitable function in your code, which is not really trivial. You may want to check whether libraries are available for that.

In practice you probably want to implement a maximum number of iterations in case someone runs it on a function without a root.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download