- In order for multiple plots to display on the axes, you will need to use the 'hold on' command.
- 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.
- 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'.
- Since the value of 'n' represents the stage within Newton's method, it may make more sense to plot it as the x-value.

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

37 views (last 30 days)

Show older comments

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 Comments

### Answers (2)

Duncan Lilley
on 13 Dec 2017

If you are trying to plot each stage of Newton's method, here are some suggestions:

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 Comments

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 Comments

### See Also

### Categories

### Community Treasure Hunt

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

Start Hunting!