Newton Raphson:用户可以输入函数吗?
Newton Raphson: Can the user input the function?
[这张图片是我的 python Newton-Raphson 方法代码。问题在于数学函数和导数。目前我是指定函数及其导数的人。有没有办法让用户输入 he/she 想要的功能?
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)
您可以使用lambda
和eval
让用户输入函数及其导数。我假设您使用的是 Python 3。如果您使用的是 Python 2,请将 input
替换为 raw_input
。
if __name__ == '__main__':
f = lambda x : eval(input())
f_ = lambda x : eval(input())
print(newtonraphson(f, f_, 3))
现在,让您的用户在 x
中输入一个表达式。请记住,输入中只允许已定义的名称。
[这张图片是我的 python Newton-Raphson 方法代码。问题在于数学函数和导数。目前我是指定函数及其导数的人。有没有办法让用户输入 he/she 想要的功能?
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)
您可以使用lambda
和eval
让用户输入函数及其导数。我假设您使用的是 Python 3。如果您使用的是 Python 2,请将 input
替换为 raw_input
。
if __name__ == '__main__':
f = lambda x : eval(input())
f_ = lambda x : eval(input())
print(newtonraphson(f, f_, 3))
现在,让您的用户在 x
中输入一个表达式。请记住,输入中只允许已定义的名称。