the answer should be done in matlab only please The \"divide and average\" metho
ID: 3194920 • Letter: T
Question
the answer should be done in matlab only please
The "divide and average" method, an old-time method for approximating the square root of any positive number a, can be formulated as x +a/x Write a well-structured M-file function based on the while...break loop structure to implement this algorithm. Use proper indentation so that the structure is clear. At each step estimate the error in your approximation as new-X XXold new Repeat the loop until 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. For example, the square root of-4 would return 21, Test your program by evaluating a = 0210 and-4 for = 1 x 10-4 , ,Explanation / Answer
function root(n,e)
N = abs(n);
x(1) = N;
eps = 100;
i = 1;
while eps>e
i=i+1;
x(i) = (x(i-1)+N/x(i-1))/2;
eps = abs((x(i)-x(i-1))/x(i));
end
if n < 0
x(i) = x(i)*sqrt(-1);
fprintf('Square-root: %fi Error: %d ',imag(x(i)),eps);
elseif n == 0
x(i) = 0;
fprintf('Square-root: %f Error: %d ',x(i),eps);
else
fprintf('Square-root: %f Error: %d ',x(i),eps);
end
Sample Input 1: Sample Output 1:
root(-4,10^-3); Square-root: 2.000000i
Error: 3.048316e-04
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.