Advertisement
frolkin28

newton_method

Feb 13th, 2020
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.15 KB | None | 0 0
  1. from math import fabs
  2.  
  3. e = 10e-3
  4.  
  5.  
  6. def newton_method(x0, f, df):
  7.     x1 = x0 - f(x0) / df(x0)
  8.     iteration = 1
  9.     print('k | x(k) | F(x(k)) | dF(x(k)) | -F/dF')
  10.     print('iter: {} | {} | {} | {} | '.format(iteration, x1, f(x1), df(x1), -f(x1)/df(x1)))
  11.     while fabs(x1 - x0) >= e:
  12.         iteration += 1
  13.         x0 = x1
  14.         x1 = x1 - f(x1) / df(x1)
  15.         print('iter: {} | {} | {} | {} | '.format(iteration, x1, f(x1), df(x1), -f(x1)/df(x1)))
  16.     return x1, iteration
  17.  
  18.  
  19. def main():
  20.     intervals = [(-2, -1), (-1, 0), (0, 1)]
  21.     def function(x): return x ** 3 + x ** 2 - x - 0.5
  22.     def dfunction(x): return 3 * x ** 2 + 2 * x - 1
  23.  
  24.     # newton method
  25.     print('Newton method')
  26.  
  27.     res, iterations = newton_method(intervals[0][0], function, dfunction)
  28.     print('Root = {}, {} iterations'.format(res, iterations))
  29.  
  30.     res, iterations = newton_method(intervals[1][1], function, dfunction)
  31.     print('Root = {}, {} iterations'.format(res, iterations))
  32.  
  33.     res, iterations = newton_method(intervals[2][1], function, dfunction)
  34.     print('Root = {}, {} iterations'.format(res, iterations))
  35.  
  36.  
  37. if __name__ == '__main__':
  38.     main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement