Matlab Tutorials | Examples
Practice 3:
Finding Root of a Number by Newton-Raphson Method
In numerical analysis, Newton’s method (also known as the Newton– Raphson method), named after Isaac Newton and Joseph Raphson, is perhaps the best known method for finding successively better approximations to the zeroes (or roots) of a real-valued function. Newton’s method can often converge remarkably quickly; especially if the iteration begins “sufficiently near” the desired root.
Given a function ƒ(x) and its derivative ƒ ‘(x), we begin with a first guess x0. A better approximation x1 is:
This iterative solution can be used in finding the root of a number. Take f(x) and f ′(x)
as:
For example, if a=400, this iteration should give x approximately as 20.
Write a MatLab code that will do the following:
- Get a number of iterations, the initial guess, and ε from the user.
- Find the root by using the Newton-Raphson method.
- Find the exact root using the sqrt() function.
- If the difference between the real root (found in step 3) and the root found by
Newton-Raphson method is smaller than ε, display the root; otherwise, display “the root could not be found”.
Use only scalar variables; no vectors or matrices. ε (epsilon) is the sensitivity, which is used to test the accuracy of the solution.
Solution:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
clc clear a = input('Enter a: ');%Inputs i = input('Enter number of iterations: '); x = input('Enter initial guess: '); e = input('Enter epsilon: '); for n=1:i x = x - (((x^2) - a) / (2*x)); %iterations end error=abs(x-sqrt(a)); %difference between previous approximation and new approximation in newtorn rapson method. if error<e % checking error fprintf('The root of the function is at %g Error is %g',x,error); else fprintf('Root can not be found error is %g',error); end |