Guest User

Untitled

a guest
Apr 12th, 2025
23
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.19 KB | None | 0 0
  1. import numpy as np
  2.  
  3. def f(x):
  4. # Nonlinear system
  5. x_val, y_val = x[0], x[1]
  6. f1 = 4 * x_val - 2 * x_val * y_val
  7. f2 = 2 * y_val + x_val * y_val - 2 * y_val**2
  8. return np.array([f1, f2])
  9.  
  10. def J(x):
  11. # Jacobian of the system
  12. x_val, y_val = x[0], x[1]
  13. j11 = 4 - 2 * y_val
  14. j12 = -2 * x_val
  15. j21 = y_val
  16. j22 = 2 + x_val - 4 * y_val
  17. return np.array([[j11, j12],
  18. [j21, j22]])
  19.  
  20. def newton_method(initial, iterations):
  21. x = np.array(initial, dtype=float)
  22. history = [x.copy()]
  23. for _ in range(iterations):
  24. F = f(x)
  25. Jx = J(x)
  26. # Add small regularization to avoid singular matrix
  27. reg = 1e-10
  28. Jx += reg * np.eye(Jx.shape[0])
  29. # Solve J * dx = F for dx, then update
  30. dx = np.linalg.solve(Jx, F)
  31. x = x - dx
  32. history.append(x.copy())
  33. return history
  34.  
  35. # Run Newton's method for 20 iterations and print the last 10 iterations
  36. if __name__ == '__main__':
  37. iterations = 20
  38. history = newton_method([1, 1], iterations)
  39. for i, sol in enumerate(history[-10:], start=len(history)-10):
  40. print(f"Iteration {i}: x = {sol[0]}, y = {sol[1]}")
  41.  
Advertisement
Add Comment
Please, Sign In to add comment