In: Advanced Math
The “divide and average” method, 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 well-structured M-file function based on the while…break loop structure to implement this algorithm. At each step estimate the error in your approximation as
ε = abs(( Xnew − Xold )/Xnew
Repeat the loop until e is less than or equal to a specified value. 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. Test your program by evaluating a = 0, 2, 10 and -4 for ε = 1×10−4. Hint: This is similar to the IterMeth function discussed in class.
%%Matlab code for finding square root of a number
clear all
close all
val=square_root(0,10^-10);
fprintf('root of 0 is ')
disp(val)
val=square_root(2,10^-10);
fprintf('root of 2 is ')
disp(val)
val=square_root(10,10^-10);
fprintf('root of 10 is ')
disp(val)
val=square_root(-4,10^-10);
fprintf('root of -4 is ')
disp(val)
%function for square root of n
function val=square_root(n,es)
%check for negative number input
if n<=0
n=abs(n);
t=1;
else
t=0;
end
x=n;
y=1;
while abs(x-y)/abs(y)>es
x=(x+y)/2;
y=n/x;
end
if t==0
val=x;
else
val=complex(0,x);
end
end
%%%%%%%%%%% End of Code
%%%%%%%%%%