필터 지우기
필터 지우기

Babylonian algorithm - square root of a number

조회 수: 11 (최근 30일)
Francesco Rossi
Francesco Rossi 2019년 10월 21일
댓글: Francesco Rossi 2019년 10월 22일
Dear all,
I am trying to bulid a function that should calculate the square root o a positive number. Unfortunatly I cannot run the code as expected.
Does anyone spot the error? Thank you in advance.
function y=sqrtB(x)
% It returns a row vector containing the approximation of the square roots of the elements of x.
% Using the Babylonian method.
% with precision 10^-10
%
% INPUT x ... 1xn vector of positive numbers
%
% OUTPUT y ... 1xn vector of square roots of x
%format long
xn=x./2; %starting number
err=abs(xn-x./xn); % the absolute error
while any(err > 1e-10) % upper bundary for the absolute error (vector compatible)
xn = 0.5 .* (xn + x./xn);
err=abs(xn-x./xn);
%disp(err);
end
y=xn;
disp(x);
disp(y);
end

채택된 답변

Stephan
Stephan 2019년 10월 21일
편집: Stephan 2019년 10월 21일
What is the problem - works for me:
y = sqrtB([16 4 9]);
function y=sqrtB(x)
% It returns a row vector containing the approximation of the square roots of the elements of x.
% Using the Babylonian method.
% with precision 10^-10
%
% INPUT x ... 1xn vector of positive numbers
%
% OUTPUT y ... 1xn vector of square roots of x
%format long
xn=x./2; %starting number
err=abs(xn-x./xn); % the absolute error
while any(err > 1e-10) % upper bundary for the absolute error (vector compatible)
xn = 0.5 .* (xn + x./xn);
err=abs(xn-x./xn);
%disp(err);
end
y=xn;
disp(x);
disp(y);
end
i get correct results by calling the function properly.
  댓글 수: 4
Stephan
Stephan 2019년 10월 22일
편집: Stephan 2019년 10월 22일
what shows up if you enter the following in the command window:
which format -all
Francesco Rossi
Francesco Rossi 2019년 10월 22일
OMG, thank you!!

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

추가 답변 (0개)

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by