- 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?
2 次查看(过去 30 天)
显示 更早的评论
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 个评论
回答(2 个)
Duncan Lilley
2017-12-13
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 个评论
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
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Annotations 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!