Error in a code which computes sqrt(a)

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

댓글 수: 4

Adam
Adam 2020년 2월 25일
편집: Adam 2020년 2월 25일
Please give more information. Just saying it 'does not work' isn't much use to anyone wanting to help.
For a start though, na does not exist so that line will error immediately, irrespective of what the rest of the code may do.
This line also does not make sense, for numerous reasons:
X(n+1) = (a + (X(n)*X(n-1))/(X(n)+X(n-1)));
X also does not exist and you can't simply past an equation into Matlab and expect it to behave as code. I'm pretty sure the calculation of x(n+1) is what the while loop is supposed to be for.
Anastasia Kyriakou
Anastasia Kyriakou 2020년 2월 25일
Unrecognized function or variable 'X'.
Error in mySqrt (line 7)
X(n+1) = (a + (X(n)*X(n-1))/(X(n)+X(n-1))); %find the second term
Yes for Na i know i deleted it
Anastasia Kyriakou
Anastasia Kyriakou 2020년 2월 25일
do i have to write X(n+1) in terms of sqa etc?
When you have a sequence in which the next term is defined in terms of the previous one you have to initialise the first term somehow, otherwise there is no previous term for the first case, to get the whole sequence going. In your case your next term is based on two previous terms, which is why you are given the first two terms of the sequence in the question so that you can then loop round increasing n and referrinig to the previous two terms, which will exist if you insert them as e.g.
X = [ 0 a ];

댓글을 달려면 로그인하십시오.

답변 (1개)

Samatha Aleti
Samatha Aleti 2020년 2월 28일

0 개 추천

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

카테고리

도움말 센터File Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

태그

질문:

2020년 2월 25일

답변:

2020년 2월 28일

Community Treasure Hunt

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

Start Hunting!

Translated by