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 に答える