Reputation: 25
[This image here is my python code for the Newton-Raphson method. The problem is with the mathematical function and the derivative. At the moment I am the one who specifies the function and its derivative. Is there any way to get the user to input the function that he/she desires?
import math
""" f: function, f_ : derivative of function, x0: initial guess, errortolerance: tolerance, maxIter: max number of iterations """
def newtonraphson(f, f_, x0, errortolerance=0.00001, maxIter=100):
"""
Take a function f, its derivative f_, initial value x0, TOL and NMAX,
and returns the root(s) of the equation using the NR method
"""
n = 1 #initial numebr of iterations
while n<=maxIter: # check while n less than maxIter
x1 = x0 - (f(x0)/f_(x0)) #newtonraphson formula
if x1 - x0 < errortolerance:
return x1
else:
x0 = x1
return False
if __name__ == "__main__":
def func(x): #initial function
return 5*math.pow(x,2) - 8*math.pow(x,1) + 4
def func_(x): #its derivative
return 10*math.pow(x,1) - 8
resNR = newtonraphson(func,func_,3) #result of newtonraphson
print(resNR)
Upvotes: 2
Views: 973
Reputation: 461
You can use lambda
and eval
to let the user input the function and its derivative. I assume you are using Python 3. If you are using Python 2, replace input
with raw_input
.
if __name__ == '__main__':
f = lambda x : eval(input())
f_ = lambda x : eval(input())
print(newtonraphson(f, f_, 3))
Now, have your user enter an expression in x
. Remember, only the already defined names are allowed in the input.
Upvotes: 1