Newton-Raphson Method: Root Finding and Convergence Visualization in Python

By Yash Kavaiya
$9
Subjects:
Maths (Algebra)
Level:
Intermediate, Expert, Bachelors/Undergraduate, Masters/Postgraduate, Doctorate/PhD
Types:
Activity, Assessment, Script
Language used:
English

This project demonstrates the Newton-Raphson method, a powerful numerical technique for finding approximate roots of real-valued functions. The method is used to solve nonlinear equations by iteratively refining an initial guess until it converges to a root within a specified tolerance. In this project, we implement the Newton-Raphson method, including its mathematical formula, and visualize its convergence to the root using Python's matplotlib library.

Code Explanation:

  1. Importing Necessary Libraries: We start by importing numpy and matplotlib.pyplot for numerical operations and plotting, respectively.

  2. Newton-Raphson Function: The newton_raphson function is defined to perform the root-finding using the Newton-Raphson method. It takes as input the function f, its derivative df, an initial guess x0, a tolerance tol, and the maximum number of iterations max_iter.

  3. Defining the Target Function and Its Derivative: In this example, we define a sample target function f(x) and its derivative df(x) that we want to find the root for. You can replace these with your own functions.

  4. Initializing Variables: We set up the initial guess, tolerance, and maximum iteration variables.

  5. Iterative Root-Finding and Convergence Tracking: We initialize an empty list x_values to store the values of x at each iteration. The main loop iteratively applies the Newton-Raphson formula to update the approximation of the root and appends the x values to x_values. It stops when the root is found within the specified tolerance or when it reaches the maximum number of iterations.

  6. Plotting the Convergence: We use matplotlib to create a plot that shows the convergence of the Newton-Raphson method. The x-axis represents the number of iterations, and the y-axis represents the approximate root value. Each point on the plot corresponds to an iteration of the method.

  7. Displaying the Result: After the loop, we check if the root was found within the tolerance and print the result accordingly.

Product preview

Product/Solution

No reviews yet.