필터 지우기
필터 지우기

I not able to understand what type error I am making in the while loop

조회 수: 1 (최근 30일)
Manav Divekar
Manav Divekar 2021년 11월 4일
댓글: Rik 2021년 11월 6일
I want to use babyloniansqrt to work if Error value should be grater than threshold and this will update the x and E value, using xnext = (x+S./x)/2, E = abs(S-xnext.^2) formula. Please check my code and let me know what I am doing wrong
function out = babyloniansqrt(S,threshold)
x = 1;
if ~exist('threshold','var')
threshold = 0.00001;
end
E = abs(S-x.^2);
while ~(E<threshold)
xnext = (x+S./x)/2;
E = abs(S-xnext.^2);
end

답변 (1개)

Rik
Rik 2021년 11월 4일
편집: Rik 2021년 11월 6일
You aren't updating the value itself, so the calculation is the exact same on every iteration.
function out = babyloniansqrt(S,threshold)
%Write lead line here
%
% write usage instructions and explanation here
x = 1;
if nargin<2
%set default threshold if not provided
threshold = 10^-5;
end
E = inf; %set initial value to enter the loop
while E>threshold
x = (x+S./x)/2;
E = abs(S-x.^2);
end
out=x;
end
  댓글 수: 3
Jan
Jan 2021년 11월 5일
Change "E = abs(S-xnext.^2);" to "E = abs(S-x.^2);" in Rik's code.
Rik
Rik 2021년 11월 6일
Thanks for the correction Jan, I have edited my answer.

댓글을 달려면 로그인하십시오.

카테고리

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

제품


릴리스

R2021a

Community Treasure Hunt

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

Start Hunting!

Translated by