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

조회 수: 15 (최근 30일)
Sreenath Umagandhi
Sreenath Umagandhi 2017년 12월 6일
답변: Yujun Sun 2018년 11월 13일
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!

답변 (2개)

Duncan Lilley
Duncan Lilley 2017년 12월 13일
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.

Yujun Sun
Yujun Sun 2018년 11월 13일
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

카테고리

Help CenterFile Exchange에서 Annotations에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by