2011-12-05 15 views
0

は私が助けをコミュニティの多くを求めてきた発行し、私はそれをすべてに感謝Pythonのニュートン法は

だから、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

それについては何が問題ですか? –

+0

私はそれを実行した後何かのようにハングアップしますが、何も出ません。実際に何が間違っているのか見ていませんでした。imはPythonに新しい構文エラーや何かがあると仮定しています。 – Shantanu

+0

ループの各ステップで値を置き換えるべきではありませんか? –

答えて

1

あなたがここに無限ループになっている:

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

そして、あなたのループ条件は次のとおりです。

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 

重要このループの部分があると思われますabs(x1-x2) < .0001ですので、これを書き直してみましょう:

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

だからおそらくx2 -= (func1sub/func1dsub)x2を間違った方法で押し込んでいます。私はこのようなprint文を追加し、値が実際に収束していることを確認したい:

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

が、私はニュートン法とその慣れていないんだけど、あなたのコードに変更することはありませんfunc1sub/func1dsubが、それはいけません反復ごとに変更しますか?

+0

@Shantanuまた、while while while:0の代わりに0 ==:を使用し、コードからdir(sympy)を取り除く - そのままのことは何もしません。 – jsbueno

+0

@jsbueno - これはおそらく質問に対するコメントであるべきだと思います。 –

+0

hm私はこれを行うと間違った答えが得られますが、どうすれば - =できますか? -X2 =(func1sub/func1dsub) – Shantanu

関連する問題