ESG111 MIDTERM PRACTICE EXAM
Hello, dear friend, you can consult us at any time if you have any questions, add WeChat: daixieit
ESG111 MIDTERM PRACTICE EXAM
There are many methods and algorithms to calculate the square root of a number, A. One of the oldest methods is known as Babylonian method. You may learn digit-by-digit calculation method in HS algebra which is slower than Babylonian method but easy to calculate. There is a fast algorithm developed by using iterative methods. One of the methods to approximate √A is shown in the following algorism:
1. Start with an initial guess x1, x! ≈ √A
2. The new (better) approximation is given by
x! 2
y! =
!
8
3. Compare x1 and x2 and check the difference. error = |x2 − x! |
4. If error is larger than the convergence criteria (truncation error), e, repeat step 1-3 till the criteria meets.
xn 2
yn =
n
8
|xn+! − xn | ≤ e
a) Write a function, fn_sqrt that calculates xn based on eq. 3 & 4. Inputs should be any number A and guessed number xn and output should be xn+1
b) Write a script to calculate √A till it meets the desired convergence criteria e. Ask user to input any positive integer, A and truncation error, e. Script should check that input number A meets the criteria. Call the function fn_sqrt to compute √A . xn can start from 1. Your script forces to run the step 1-3 until |xn+1 - xn | becomes smaller than e. When it meets the criteria, then loop should stop. Display the answer up to the desired decimal place (depending on truncation error, e). Use for-loop and if statement to cover all the requirements.
function X = fn_sqrt(A, x)
%This function calculate sqrt(A) based on Halley's method
%function body
%Check the formula from the exam
%Set the output as X and use input A and x in the calculation expression
end
%This is the answer key for Midterm Practice Problem
A=input( 'Input a positive integer: ');
errorT=input( 'Input truncation error: ');
%checks that A is positive or an integer
while
end
%find initial variables
%xn can start from 1 (specified in question 2)
xn=1;
%call the function fn_sqrt
xn1=fn_sqrt(A, xn);
errorC=abs(xn1-xn);
%keeps running function until convergence criteria is met
while
%always update xn to be the most recent best guess
%calculate new guess using most recent guess as input . Here assume xn1 is
the output of fn_sqrt
%calculate new error . Assume errorC is the variable for new error .
end
fprintf( '\nThe square root of %d is %.2f\n',A, xn1);
2023-05-15