Part II: Script Exercises 1. Here is a tried-and-true method for calculating the
ID: 649670 • Letter: P
Question
Part II: Script Exercises 1. Here is a tried-and-true method for calculating the square root of a positive number C using only basic arithmetic operations. The method uses two variables, Xold and Xnew, and updates the variables repeatedly until the absolute value of the difference Xold-Xnew is less than some threshold; for this question, the threshold is 0.0001. The rules for updating the variables are as follows: a. Before the loop, assign Xold = C b. Loop until the difference is below the threshold, performing these two calculations in this order. Xnew = Xold ? X^2old-C/2Xold Xold = Xnew The difference |Xold ? Xnew| is tested between these two calculations. With each successive iteration, the difference becomes less than the time before. Once the difference becomes less than the threshold, the loop should terminate and the answer (i.e.. the square root of C) is in Xnew. Implement this algorithm in MATLAB, displaying the final value. Verify that your code produces the correct answer by comparing your answer to that produced by MATLAB's sqrt function on a few test values. Allow the user to enter C. You may assume they enter this as a valid positive number. HINT: One way to solve this is to have an infinite loop, that is to force the loop to go on forever and only end via a break statement Example Run Enter a positive number: 8 Matlab sqrt: 2.8284 Algo sqrt: 2.8284Explanation / Answer
C=input('Enter a positive number: ');
Xold=C;
n=1
while n<2
Xnew = Xold - (Xold*Xold -C)/(2*Xold);
if abs(Xnew-Xold) <0.0001
n=2;
end
Xold=Xnew;
end
disp(['Matlab sqrt: ',num2str(Xnew,10)]);
disp(['Algo sqrt: ',num2str(sqrt(C),10)]);