newton_fd.py (1442B)
1 #!/usr/bin/env python3 2 # File : newton_fd.py 3 # Description: Newton's method with approximate Jacobian representation 4 # Copyright 2021 Harvard University. All Rights Reserved. 5 import numpy as np 6 7 f = lambda x: x - np.exp(-2.0 * np.sin(4.0 * x) * np.sin(4.0 * x)) 8 J = lambda x, eps: ( 9 f(x + eps) - f(x) 10 ) / eps # Finite-Difference approximation of J 11 12 13 def newton(f, J, x_k, tol=1.0e-8, max_it=100, eps=1.0e-8): 14 root = None 15 for k in range(max_it): 16 dx_k = -f(x_k) / J(x_k, eps) 17 if abs(dx_k) < tol: 18 root = x_k + dx_k 19 print(f"Found root {root:e} at iteration {k+1}") 20 print(f(root)) 21 break 22 print(f"Iteration {k+1}: Delta x = {dx_k:e}") 23 x_k += dx_k 24 return root 25 26 27 if __name__ == "__main__": 28 import argparse 29 30 def parse_args(): 31 # yapf: disable 32 parser = argparse.ArgumentParser(description="Newton-Raphson Method") 33 parser.add_argument('-g', '--initial_guess', type=float, help="Initial guess", required=True) 34 parser.add_argument('-t', '--tolerance', type=float, default=1.0e-8, help="Convergence tolerance") 35 parser.add_argument('-i', '--maximum_iterations', type=int, default=100, help="Maximum iterations") 36 # yapf: enable 37 return parser.parse_args() 38 return parser.parse_args() 39 40 args = parse_args() 41 newton(f, J, args.initial_guess, args.tolerance, args.maximum_iterations)