Python中的牛顿法
我正在用Python写一个程序,目的是用牛顿法来找出零点。我已经完成了初步版本,但后来意识到了一些不同的事情,想知道我是否需要做一些调整或改动。(对这个主题的了解可能会有帮助)
def main():
dir(sympy)
print ("NEWTONS METHOD")
print ("Write your expression in terms of 'x' ")
e = sympy.sympify(raw_input("input expression here: "))
f = sympy.Symbol('x')
func1 = e
func1d = sympy.diff(e,f)
print ("the dirivative of your function = "), func1d
x = input("number to substitude for x: ")
func1sub = func1.subs({'x':x})
func1dsub = func1d.subs({'x':x})
n = x - float(func1sub/func1dsub)
while n != x:
func1sub = func1.subs({'x':x})
func1dsub = func1d.subs({'x':x})
n = x - float(func1sub/func1dsub)
print n
main()
1) 首先,我在想,因为n
和x
的值可能并不总是完全相同,所以我需要用round函数来进行四舍五入。
2) 看完这些后,我觉得我的while循环没有解决它应该解决的问题。它应该找出什么样的x
可以代入到函数中,输出的结果也是x
。我可以通过把这些值放到一个数组里,然后看看哪个数字出现了多次来做到这一点吗?
2 个回答
2
问题1:我同意。
问题2:在循环的顶部附近写 x = n
。你想要继续进行。
2
首先,你的 while
循环里,x
的值没有变化。
其次,结束循环的标准应该是“当前”的估计值和“之前”的估计值要“足够接近”,也就是说,你应该使用类似下面的东西:
while abs(current - previous) > tolerance: