【发布时间】:2018-07-16 11:55:47
【问题描述】:
[这里的这张图片是我的 Newton-Raphson 方法的 Python 代码。问题在于数学函数和导数。目前我是指定函数及其导数的人。有没有办法让用户输入他/她想要的功能?
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。
标签: python python-3.x python-2.7 math newtons-method