【问题标题】:Python newtons method issuesPython 牛顿法问题
【发布时间】:2011-12-06 04:37:41
【问题描述】:

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

所以我一直在研究一个解决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()

【问题讨论】:

  • 它在我运行它之后就像它在做某事一样挂起,但没有任何结果。我已经查看了几个小时了,实际上并没有看到有什么问题,我假设它有一些语法错误或者对 python 来说很新。
  • 你不应该在循环的每一步替换值吗?
  • 你的意思是在每次迭代后重新添加替代品吗?
  • 这似乎更好地转移到http://codereview.stackexchange.com/
  • @moooeeeeep,代码审查只针对工作代码。此处发布的任何损坏的代码都将关闭或迁移回此处。

标签: python loops equation newtons-method


【解决方案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) &lt; .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 永远不会改变,但它不应该在每次迭代时改变吗?

【讨论】:

  • @Shantanu 也可以使用 while True: 而不是 while 0 == 0: 并从代码中删除 dir(sympy) - tis 语句不执行任何操作。
  • @jsbueno - 我认为这应该是对这个问题的评论。
  • 嗯,当我这样做时,我得到了错误的答案,但是 -= 有什么作用?是不是像写 -x2 = (func1sub/func1dsub)
  • @Shantanu - a -= ba = a - b 相同
  • 感谢对 while 循环的帮助,由于某种原因,我的代码在某处出现了一些错误,当我现在运行它时,x1 总是等于 2.0,无论什么方程,x2 都会上升每次加 1 并且不会停止
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-26
  • 2017-06-28
  • 2010-12-21
  • 1970-01-01
  • 2013-10-17
  • 2017-05-05
相关资源
最近更新 更多