Rewrite the Matlab userdefined function mybabx which was dev
Rewrite the Matlab userdefined function mybab(x), which was developed earlier in class and returns the square root of a number using the Babylonian method, in such a way that it will now include a check for the error in user input, or so called “errortrap”. This function will return two values, the square root and an integer error code. Identify all possible cases of user input error. You can use the following Matlab builtin functions a. ischar(x) which will return 1 if x is a character string, and zero otherwise b. isreal(n) which will return 1 if n is a real number, and zero otherwise Examples: y = ischar(‘My Name’); % This will make y = 1 a = 3.5; z = isreal(a); % This will make z = 1
Solution
The babylonian method uses the property of successive division to divide the number and then it is used to calculate the square root of the number. We can do the same in matlab using the inbuilt mean function.
The result will be stored in a variable result_sqrt and the while loop will run untill we get a solution which is very close to the actual solution.
function result_sqrt = mybab(x)
% dividing the number by 2
mid = x/2;
% getting one more intermediate value
mid2 = x/mid;
% we take the mean between the two values
result_sqrt = mean([mid mid2]);
% Repeat until we get a value which is close to the square root
while abs(x - result_sqrt^2) > 0.000000001
mid = result_sqrt;
mid2 = x/mid;
result_sqrt = mean([mid mid2])
end
