main file
num = input('Enter the number you want to find the square root: ');
sqroot(num);
sqroot.m
function [sq_root] = sqroot(num)
format long
converge = false;
iter = 0;
esp = 10^-10;
xn=1;
tru_err_arr = [];
est_err_arr = [];
iter_arr = [];
if num >= 1
xn =1;
while xn^2<num
xn = xn+10;
end
xn = xn/2;
else
xn =1;
while xn^2>num
xn = xn/10;
end
xn = xn*2;
end
while converge == false
f = xn^2-num;
df = 2*xn;
nr = xn -(f/df);
tru_err = sqrt(num)-xn;
err_est = nr-xn;
tru_err_arr =[tru_err_arr, tru_err];
est_err_arr =[est_err_arr, err_est];
if abs(err_est/xn)<esp
converge = true;
end
iter_arr = [iter_arr, iter];
iter = (iter+1);
xn=nr;
end
sq_root = xn;
disp(['The sqrt of ', num2str(num),' is: ' ])
disp(sq_root);
info_plot(tru_err_arr, est_err_arr, iter_arr)
end
info_plot.m
function info_plot(tru_err_arr, est_err_arr, iter_arr)
figure(1)
plot (iter_arr, abs(tru_err_arr), 'linewidth',2)
hold on
plot(iter_arr,abs(est_err_arr),'linewidth',2)
xlabel('iteration')
ylabel('Errors')
legend('True Error','Estimated Error')
title('Errors vs Graph')