11 views (last 30 days)

One of the methods to compute sqer (a) , a>0 is

X(n+1) = (a + (X(n)*X(n-1))/(X(n)+X(n-1)), n = 1, 2, …, with X0=1 and X1=a (That is, it is known that lim n-> infin of Xn = sqrt(a)

Write a function [sqa, nitr] = mySqrt(a) which implements this calculation. The function should use a while-loop, terminate when the difference between Xn+1 and Xn becomes smaller than eps(10*a), and output Xn+1 in sqa and the value of n at which the while-loopwas terminated in nitr. Test your function for a = 103041

I have written this but it does not work

function [sqa, nitr] = mySqrt (a)

%[sqa, nitr] = mySqrt (a)

% computes square root of a

% sqa = a;

sqaprev = a;

nitr = 0;

X(n+1) = (a + (X(n)*X(n-1))/(X(n)+X(n-1))); %find the second term

sqa= X(n+1)

while abs (sqaprev-sqa) >= eps (10*a)

sqaprev = sqa;

sqa = (1/2) *(sqaprev+ (a/sqaprev));

nitr = nitr + 1;

end %while

end

Samatha Aleti
on 28 Feb 2020

You may need to initialize the variables "sqaprev", "sqa" as follows:

function [sqa, nitr] = mySqrt (a)

sqaprev = 0;

sqa= a;

nitr = 0;

while abs (sqaprev-sqa) >= eps (10*a)

sqaprev = sqa;

sqa = (1/2) *(sqaprev+ (a/sqaprev));

nitr = nitr + 1;

end

end

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!
## 4 Comments

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/507444-error-in-a-code-which-computes-sqrt-a#comment_801972

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/507444-error-in-a-code-which-computes-sqrt-a#comment_801972

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/507444-error-in-a-code-which-computes-sqrt-a#comment_801976

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/507444-error-in-a-code-which-computes-sqrt-a#comment_801976

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/507444-error-in-a-code-which-computes-sqrt-a#comment_801981

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/507444-error-in-a-code-which-computes-sqrt-a#comment_801981

## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/507444-error-in-a-code-which-computes-sqrt-a#comment_802033

⋮## Direct link to this comment

https://in.mathworks.com/matlabcentral/answers/507444-error-in-a-code-which-computes-sqrt-a#comment_802033

Sign in to comment.