Write a Matlab script that answers the following questions. \"Divide and average
ID: 1715388 • Letter: W
Question
Write a Matlab script that answers the following questions.
"Divide and average", an old-time method for approximating the square root of any positive number "a", can be formulated as x = x+ a/x/2 Write a MATLAB function to implement this algorithm. At each step estimate the error in your approximation as epsilon = | x new - xold / x new | Repeat the loop until e is less than or equal to a specified tolerance. Design your program so that it returns both the result and the error. Make sure that it can evaluate the square root of numbers that are equal to and less than zero. For the latter case, display the result as an imaginary number. For example, the square root of -4 would return 2i where i is root over -1 Details about the MATLAB function: Function Name: sqrtApp Inputs: a, tol a: Function sqrtApp approximates the square root of number a. tol: Error of the approximation has to be less than a user-defined tolerance tol. Outputs: sqrt_a, EApp sqrt_a: Approximation of square root of a. EApp: Error of the approximation. Hints for the Matlab function: Take baby steps!! First write your function assuming that input a is always positive. After you are done with this part, rewrite your function and this time make sure that it can evaluate the square root of numbers that are equal to and less than zero. (This is just a recommendation if you are really comfortable with MATLAB you do not have to take baby steps.) Initialize x in Eq. (1) to be |a| You can think of Eq. (1) as follows: x new = x old + a/old / 2.Explanation / Answer
function root = sqrtam(num, tolerance)
%Program was run on Matlabr2015a
%save the code in sqrtam.m file
%usage eg: sqrtam(25,0.001)
%Tolerance and required number
a=num;
tol=tolerance;
% ind variable for differentiating complex and real numbers
ind=0;
%complex and real number check
if(a>=0)
x=a;
ind=1;
else
a = abs(a);
x = a;
ind=-1;
end
%error variable
err=0;
% square root loop
while(1)
y = (x+(a/x))/2;
err = abs((y-x)/y);
if(err<=tol)
break;
else
x=y;
end
end
%conversion to complex number if required number is negative
if(ind==1)
disp(y);
else
y=(y)*1i;
disp(y);
end
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.