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:
Importing Necessary Libraries: We start by importing numpy and matplotlib.pyplot for numerical operations and plotting, respectively.
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.
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.
Initializing Variables: We set up the initial guess, tolerance, and maximum iteration variables.
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.
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.
Displaying the Result: After the loop, we check if the root was found within the tolerance and print the result accordingly.
No reviews yet.