Babylonian algorithm - square root of a number

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

 Akzeptierte Antwort

Stephan
Stephan am 21 Okt. 2019
Bearbeitet: Stephan am 21 Okt. 2019

1 Stimme

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 Kommentare

I get this error message: Undefined function 'fomat' for input arguments of type 'char'.
if I run it (i.e.)
format long
sqrtB(100)
James Tursa
James Tursa am 22 Okt. 2019
Did you really misspell 'format' as 'fomat'?
Stephan
Stephan am 22 Okt. 2019
Bearbeitet: Stephan am 22 Okt. 2019
what shows up if you enter the following in the command window:
which format -all
OMG, thank you!!

Melden Sie sich an, um zu kommentieren.

Weitere Antworten (0)

Kategorien

Mehr zu Scope Variables and Generate Names finden Sie in Hilfe-Center und File Exchange

Produkte

Tags

Community Treasure Hunt

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

Start Hunting!

Translated by