cs107-lecture-examples

Example codes used during Harvard CS107 lectures
git clone https://git.0xfab.ch/cs107-lecture-examples.git
Log | Files | Refs | README | LICENSE

newton.py (1394B)


      1 #!/usr/bin/env python3
      2 # File       : newton.py
      3 # Description: Newton's method with exact 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: 1.0 + 16.0 * np.exp(-2.0 * np.sin(4.0 * x)**2
      9                                  ) * np.sin(4.0 * x) * np.cos(4.0 * x)
     10 
     11 
     12 def newton(f, J, x_k, tol=1.0e-8, max_it=100):
     13     root = None
     14     for k in range(max_it):
     15         dx_k = -f(x_k) / J(x_k)
     16         if abs(dx_k) < tol:
     17             root = x_k + dx_k
     18             print(f"Found root {root:e} at iteration {k+1}")
     19             break
     20         print(f"Iteration {k+1}: Delta x = {dx_k:e}")
     21         x_k += dx_k
     22     return root
     23 
     24 
     25 if __name__ == "__main__":
     26     import argparse
     27 
     28     def parse_args():
     29         # yapf: disable
     30         parser = argparse.ArgumentParser(description="Newton-Raphson Method")
     31         parser.add_argument('-g', '--initial_guess', type=float, help="Initial guess", required=True)
     32         parser.add_argument('-t', '--tolerance', type=float, default=1.0e-8, help="Convergence tolerance")
     33         parser.add_argument('-i', '--maximum_iterations', type=int, default=100, help="Maximum iterations")
     34         # yapf: enable
     35         return parser.parse_args()
     36 
     37     args = parse_args()
     38     newton(f, J, args.initial_guess, args.tolerance, args.maximum_iterations)