Converting a Script to a Function The script squarerootm was
Solution
% matlab code to determine square roo of a number
% This function computes the square root of a number
% using the \"successive approximation method.\"
function squareRoot = square_root(A)
old_length = A; %initial length = A
new_length = 1; %initial width = 1
k = 0; % loop counter
loop_tolerance = 0.00001;
while abs(new_length - old_length) > loop_tolerance
old_length = new_length;
new_length = (old_length + A/old_length)/2;
k = k + 1; % loop counter
end
squareRoot = new_length;
end
% main code, the function will be called from this main body
A = input(\'Enter a positive number to estimate its square root: \');
while A <= 0
disp(\'Invalid entry. The number cannot be zero or negative!\')
A = input(\'Enter a positive number to estimate its square root: \');
end
loop_tolerance = 0.00001;
% function call
squareRoot = square_root(A);
fprintf(\'The square root of %0.2f is approximately %0.6f (to a tolerance of %0.5f).\ \', A, squareRoot, loop_tolerance);
%{
output:
Enter a positive number to estimate its square root: 25
The square root of 25.00 is approximately 5.000000 (to a tolerance of 0.00001).
Enter a positive number to estimate its square root: 46
The square root of 46.00 is approximately 6.782330 (to a tolerance of 0.00001).
%}
