Advertisement
Pug_coder

Untitled

Jun 13th, 2023
16
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.76 KB | None | 0 0
  1. import numpy as np
  2.  
  3.  
  4. def equation(x):
  5. return 2 * x**3 + 2 * x**2 - 2 * x - 7
  6.  
  7.  
  8. def derivative(x):
  9. return 6 * x**2 + 4 * x - 2
  10.  
  11.  
  12. def newton_method(initial_guess, tolerance=1e-3, max_iterations=100):
  13. x = initial_guess
  14. for iteration in range(max_iterations):
  15. delta = equation(x) / derivative(x)
  16. x_k = x - delta
  17. #x -= delta
  18.  
  19. if equation(x_k) * equation(x_k + np.sign(x_k - x)*tolerance) < 0:
  20. return x_k, iteration
  21.  
  22. x = x_k
  23. raise ValueError("The method did not converge")
  24.  
  25. # Solve the equation using Newton's method
  26. initial_guess = 1.0
  27. root, iteration = newton_method(initial_guess)
  28. print("Root:", root)
  29. print("Value at the root:", equation(root))
  30. print("Iterations:", iteration)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement