フィルターのクリア

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

1 回表示 (過去 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 Center および File ExchangeAnnotations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by