Python牛顿法问题

0 投票
1 回答
728 浏览
提问于 2025-04-17 07:45

我一直在向大家求助,非常感谢大家的帮助。

我正在用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()

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 的值从来没有变化,但它不是应该在每次循环时都改变吗?

撰写回答