Advertisement
ImperfectionistCoder

Newton avec iteration

Jun 25th, 2021
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.04 KB | None | 0 0
  1. def f(x):
  2.     return (2*x**4+x**2+2)/(x**4+1)
  3.  
  4. def f_prime(x):
  5.     return -4*x**3*(2*x**4 + x**2 + 2)/(x**4 + 1)**2 + (8*x**3 + 2*x)/(x**4 + 1)
  6.  
  7.  
  8. def f_2prime(x):
  9.     return 32*x**6*(2*x**4 + x**2 + 2)/(x**4 + 1)**3 - 8*x**3*(8*x**3 + 2*x)/(x**4 + 1)**2 -12*x**2*(2*x**4 + x**2 + 2)/(x**4 + 1)**2 + (24*x**2 + 2)/(x**4 + 1)
  10. def newton_f_opt(x0, f_prime, f_2prime, maxiter = 100, tol = 0.0001):
  11.     x = x0
  12.     Nter = 0
  13.     for i in range(maxiter):
  14.         Nter += 1
  15.         x_next = x - (f_prime(x)/f_2prime(x))
  16.         if x_next - x < tol:
  17.             return x_next, Nter+1
  18.             print('Optimization terminated successfully.')
  19.             print('Current parameter value: ' + str(x))
  20.             print('Iterations: ' + str(i))
  21.             break
  22.         x = x_next
  23.        
  24.     if i == maxiter - 1 and x_next - x < tol:
  25.         print('Optimization terminated after maximum number of iterations.')
  26.    
  27.     return x, Nter+1
  28.  
  29. x_star, Niter = newton_f_opt(0, f_prime, f_2prime)
  30.  
  31. print(x_star)
  32. print(f(x_star))
  33. print(Niter)
  34.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement