Asked by Francesco Rossi
on 21 Oct 2019 at 19:47

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

Answer by Stephan
on 21 Oct 2019 at 20:36

Edited by Stephan
on 21 Oct 2019 at 20:38

Accepted Answer

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.

James Tursa
on 22 Oct 2019 at 0:41

Did you really misspell 'format' as 'fomat'?

Stephan
on 22 Oct 2019 at 0:46

what shows up if you enter the following in the command window:

which format -all

Francesco Rossi
on 22 Oct 2019 at 5:21

OMG, thank you!!

Sign in to comment.

Opportunities for recent engineering grads.

Apply Today
## 0 Comments

Sign in to comment.