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)