Write funtion mysqrt which computes and returns the square root (r) of a number
ID: 3565920 • Letter: W
Question
Write funtion mysqrt which computes and returns the square root (r) of a number by using Newton's iterative method for evaluating VTC : 1 rk = (rk?i 2 rk- 1 Function should be called with 1, 2 or 3 arguments: r = mysqrt(x) r = mysqrt(x,delta) r = mysqrt(x,delta,maxit) where: x = number for which the square root is desired delta = (optional) convergence tolerance. Default: delta =5.10 -6 maxit = (optional) maximum number of iterations. Default: maxit =25 Iterations should be terminated after maxit iterations or when: irk-i ? rkiExplanation / Answer
%Save it as mysqrt.m
function [ y ] = mysqrt( x,delta,maxit )
if nargin <3
maxit=25;
end
if nargin<2
delta=5*10^-6;
end
r=zeros(maxit,1);
r(2)=x;
r(1)=2*r(2);
k=2;
err=abs(r(1)-r(2))/r(1);
while k<=maxit && err>delta
r(k)=1/2*(r(k-1)+x/(r(k-1)));
err=abs(r(k-1)-r(k))/r(k-1);
k=k+1;
end
y=r(k-1);
end
% mysqrt(4)
%ans =
% 2.0000
%mysqrt(400)
%ans =
% 20
%mysqrt(4*10^-16)
%ans =
%3.4147e-08
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.