somebody help me please! I've gone over the irritation of approx_sqrt and the only way I've got each value of the function while using a calculator it was if I used y=2
조회 수: 4 (최근 30일)
이전 댓글 표시
format long g
approx_sqrt(2)
function y=approx_sqrt(x)
y=x;
while abs(y^2-x)>0.001*x
y=(x/y+y)/2
end
end
댓글 수: 7
John D'Errico
2023년 2월 21일
Seriously. Your code is correct. Have more confidence in yourself. You got it right.
답변 (1개)
John D'Errico
2023년 2월 22일
편집: John D'Errico
2023년 2월 22일
The site seems to want an answer to your question, and we just answered you in the comments. Oh well.
But seriously, your solution is correct. This is indeed Newton's method, as applied to the square root. For example, if I run your code, we see this (actually, I changed the congergence tolerance so it would iterate at least one more time, but the code is the same):
format long g
approx_sqrt(3)
sqrt(3)
What do we know about Newton's method? It has quadratic convergence near a single root. One thing that tells us is as we get near to the solution, you should expect to see double the number of correct digits with each iteration.
So the first iteration started out at y=2. Then we see 1.75, so 2 significant digits are correct. The next iteration gave us 1.732, so with 4 correct digits. The next iteration has the approximation at 1.73205081, so the firsy 8 digits are correct. And then the final iteration gave us essentially full double precision accuracy.
function y=approx_sqrt(x)
y=x;
while abs(y^2-x)>1e-14*x
y=(x/y+y)/2
end
end
Again, this is exactly how that method should work. It did exactly what I would expect. (And the equations you used are correct.)
댓글 수: 0
참고 항목
카테고리
Help Center 및 File Exchange에서 Matrix Indexing에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!