0

我一直在向社区寻求帮助,我很感激

所以我一直在研究一个解决python中牛顿方法的程序,但由于某种原因它不起作用,有人可以看看吗?谢谢你=)

import sympy
from collections import defaultdict

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) #takes the dirivative of the function
   print ("the dir of your function = "), func1d
   x = input("number to substitute for x: ")
   a = input("how many digits would you like to round to [recomended at least 4]") 
   func1sub = func1.subs({'x':x})   #substitutes the user given value of x into the equation
   func1dsub = func1d.subs({'x':x}) #substitutes the user given value of x into the equation
   func1sub = float(func1sub) 
   func1dsub = float(func1dsub)
   func1sub = round(func1sub)
   func1dsub = round(func1dsub)
   round(func1sub,a)
   round(func1dsub,a)
   n = x - (func1sub/func1dsub)
   x1 = 0
   x2 = 0 
   n = x - (func1sub/func1dsub)  
   x1 = n 
   x1 = round(x1) 
   n = x2 - (func1sub/func1dsub)
   x2 = n 
   x2 = round(x2)
   while 0 == 0:
      if abs(x1-x2) < .0001:
         print x1
         break
      else:
         n = x2 - (func1sub/func1dsub)
         x2 = n 
      if abs(x - n) < .03:
         print x
   if func1dsub == 0:  
      print ("ERROR CAN NOT DIVIDE BY 0") 
main()
4

1 回答 1

1

你在这里得到一个无限循环:

while 0 == 0:

    if abs(x1-x2) < .0001:
        print x1
        break

    else:
        n = x2 - (func1sub/func1dsub)
        x2 = n 

    if abs(x - n) < .03:
        print x

这个循环中重要的部分似乎是:

n = x2 - (func1sub/func1dsub)
x2 = n 

你的循环条件是abs(x1-x2) < .0001,所以让我们重写一下:

while abs(x1 - x2) >= .0001:
    x2 -= (func1sub / func1dsub)
print x1

所以也许x2 -= (func1sub / func1dsub)是推x2错了方向。我会添加这样的打印语句,并确保这些值实际上是收敛的:

while abs(x1 - x2) >= .0001:
    x2 -= (func1sub / func1dsub)
    print (x1, x2)

另外,我对牛顿的方法不是很熟悉,但是在你的代码中func1sub / func1dsub永远不会改变,但它不应该在每次迭代中改变吗?

于 2011-12-05T20:10:33.290 回答