Guest User

Newton-Raphson Method

a guest
Sep 21st, 2012
653
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.89 KB | None | 0 0
  1. def evaluate_poly(poly, x):
  2.     valpoly = 0
  3.     for i in range(0, len(poly)):
  4.         valpoly = valpoly + (poly[i]*x**i) ## changed sumpoly to valpoly
  5.     return valpoly ## return the value of poly at x
  6.  
  7.        
  8.                              
  9. def compute_deriv(poly):
  10.     deriv = ()
  11.     for i in range(0, len(poly)):
  12.         deriv = deriv + (poly[i]*i,)
  13.     return deriv ## function returns a tuple representation of the derivative of "poly"
  14.  
  15.  
  16.  
  17. def compute_root(poly, x_0, epsilon):
  18.     value = evaluate_poly(poly, x_0)
  19.     count = 0
  20.  
  21.     while (value > epsilon) or (value < -epsilon):
  22.         x_0 = x_0 - ((value)/(evaluate_poly(compute_deriv(poly), x_0)))
  23.         value = evaluate_poly(poly, x_0)
  24.         count += 1
  25.        
  26.     return (x_0, count)
  27.  
  28.  
  29. polyMy = (-13.39, 0.0, 17.5, 3.0, 1.0)
  30. print compute_root(polyMy, .01, .0001)
  31. ## Output should be (0.80679042259850975, 15239)
Advertisement
Add Comment
Please, Sign In to add comment