# How do I plot convergence in Newton's method to find square root?

37 views (last 30 days)
Sreenath Umagandhi on 6 Dec 2017
Answered: Yujun Sun on 13 Nov 2018
I have the following function to find the square root of a number a, in this case it is 2:
function [sqrta,n] = newton()
a = 2;
tol = 1e-10;
n = 0;
sqrta = a;
sqrtaminus1 = a;
while abs(sqrta^2 - a) > tol
sqrta = 0.5*(sqrtaminus1 + (a/sqrtaminus1));
n = n + 1;
sqrtaminus1 = sqrta;
plot(sqrta,n);
end
I run this by:
>> [sqrta,n] = newton()
I'm making some mistake while plotting for convergence. I know I am making a fatal error without understanding the concept of convergence. It'd be great if someone could help me. Thanks!
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Answers (2)

Duncan Lilley on 13 Dec 2017
If you are trying to plot each stage of Newton's method, here are some suggestions:
1. In order for multiple plots to display on the axes, you will need to use the 'hold on' command.
2. Since 'sqrtaminus1' is keeping track of the previous value of 'sqrta', it makes sense to update it before recalculating the value of 'sqrta' inside the 'while' loop.
3. In order to view the plot, either provide a line specification to draw point markers or use the 'sqrtaminus1' value to draw a line from the previous value to the newly calculated value of 'sqrta'.
4. Since the value of 'n' represents the stage within Newton's method, it may make more sense to plot it as the x-value.
Take a look at the following changes:
function [sqrta,n] = newton()
a = 2;
tol = 1e-15;
n = 0;
sqrta = a;
sqrtaminus1 = a;
axes
hold on
while abs(sqrta^2 - a) > tol
sqrtaminus1 = sqrta;
sqrta = 0.5*(sqrtaminus1 + (a/sqrtaminus1));
n = n + 1;
plot([n-1 n], [sqrtaminus1 sqrta], 'r-');
end
hold off
This will plot each stage of Newton's method.
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

Yujun Sun on 13 Nov 2018
function [sqrta,n] = newton1()
a = 2;
tol = 1e-15;
n = 0;
sqrta = a;
sqrtaminus1 = a;
axes
%hold on
while abs(sqrta^2 - a) > tol
sqrtaminus1 = sqrta;
sqrta = 0.5*(sqrtaminus1 + (a/sqrtaminus1));
n = n + 1;
plot([n-1 n], [sqrtaminus1 sqrta], 'r-');
pause(2)
end
end
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Categories

Find more on Calculus in Help Center and File Exchange

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!