0

I'm very new to coding and am working on a project where I write a code to perform newtons method for lots of different functions. The code I wrote to do newtons method is as follows:

def fnewton(function, dx, x):
    #defined the functions that need to be evaluated so that this code can be applied to any function I call
    def f(x):
        f=eval(function)
        return f
#eval is used to evaluate whatever I put in the function place when I recall fnewton
#this won't work without eval to run the functions
    def df(x):
        df=eval(dx)
        return df
    n=0
    min=.000001
    guess=2
    xi_1=guess
    #defining these variables before Fnewton so I can use them in print 
    while np.absolute((xi_1))>min:
    #basically this means that you continue the process until funct/der is greater than the tolerance
        n=n+1 #helps keep track over how many times I iterated
        x=xi_1-f(xi_1)/df(xi_1) #this is the newton eqn
        xi_1=x
    print('the root is at:')
    print(x)
    print('after this many iterations:')
    print(n)

I am trying to call on this function to operate on functions I defined before it by using the command:

fnewton("a(x)", "dadx(x)",2)

Once I added the two it would run(and tell me variables weren't defined) but now it just runs forever and never computes anything. please help, did I code wrong?

ps. a(x) and dadx(x) are:

def a(x):
    f=np.exp(np.exp(-x))-x**2+x
    return(f)

def dadx(x):
    f=(a(x+.01)-a(x))/.01
    return(f)
afg
  • 29
  • 4

3 Answers3

0

I executed the code you loop stuck at value 1.7039784148789716, your logic which says while np.absolute(xi_1)>min1: seems not working

try printing values inside the loop as below

    while np.absolute(xi_1)>min1:
    #basically this means that you continue the process until funct/der is greater than the tolerance
        n=n+1 #helps keep track over how many times I iterated
        x=xi_1-f(xi_1)/df(xi_1) #this is the newton eqn
        xi_1=x
        print(np.absolute(xi_1))

and find the proper while expression to suite your result

Dickens A S
  • 3,824
  • 2
  • 22
  • 45
0

I think you meant while np.absolute(f(xi_1))>min:

PS: just refrain yourself from using functions like eval() in python, it makes your code a lot harder to debug

Aidono
  • 1
  • 3
0

Best to write your f and df as discrete functions then pass references to them to fnewton(). In this way the implementation of fnewton() remains constant and you just have to pass your estimate and f and df references. You can reasonably hard-code Euler's Number for this trivial case which avoids the need to import numpy

e = 2.718281828459045

def f(x):
    return e**(e**(-x))-x**2+x

def df(x):
    return (f(x+.01)-f(x))/.01

def fnewton(x0, f, df, tolerance=0.0001):
    if abs(fx0 := f(x0)) < tolerance:
        return x0
    return newton(x0 - fx0/df(x0), f, df, tolerance)

print(fnewton(1.5, f, df))

Output:

1.7039788103083038
DarkKnight
  • 19,739
  • 3
  • 6
  • 22