[Python] python中使用牛顿迭代法 →→→→→进入此内容的聊天室

来自 , 2020-11-08, 写在 Python, 查看 140 次.
URL http://www.code666.cn/view/e7a561a2
  1. ''' root = newtonRaphson(f,df,a,b,tol=1.0e-9).
  2.    Finds a root of f(x) = 0 by combining the Newton-Raphson
  3.    method with bisection. The root must be bracketed in (a,b).
  4.    Calls user-supplied functions f(x) and its derivative df(x).  
  5. '''    
  6. def newtonRaphson(f,df,a,b,tol=1.0e-9):
  7.     import error
  8.     fa = f(a)
  9.     if fa == 0.0: return a
  10.     fb = f(b)
  11.     if fb == 0.0: return b
  12.     if fa*fb > 0.0: error.err('Root is not bracketed')
  13.     x = 0.5*(a + b)                    
  14.     for i in range(30):
  15.         fx = f(x)
  16.         if abs(fx) < tol: return x
  17.       # Tighten the brackets on the root
  18.         if fa*fx < 0.0:
  19.             b = x  
  20.         else:                  
  21.             a = x
  22.       # Try a Newton-Raphson step    
  23.         dfx = df(x)
  24.       # If division by zero, push x out of bounds
  25.         try: dx = -fx/dfx
  26.         except ZeroDivisionError: dx = b - a
  27.         x = x + dx
  28.       # If the result is outside the brackets, use bisection  
  29.         if (b - x)*(x - a) < 0.0:  
  30.             dx = 0.5*(b - a)                      
  31.             x = a + dx
  32.       # Check for convergence    
  33.         if abs(dx) < tol*max(abs(b),1.0): return x
  34.     print 'Too many iterations in Newton-Raphson'
  35. #//python/7409

回复 "python中使用牛顿迭代法"

这儿你可以回复上面这条便签

captcha