Error in code, a method to compute sqrt (a)

六眼飞鱼酱① 提交于 2020-04-17 22:12:15

问题


One of the methods to compute sqrt(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-loop was 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

i get the error:

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

Could someone help me ?


回答1:


You should start with declaring your variables and assigning them values

X(1)=1;
X(2)=a;
n=2;

Then in the loop you apply the given recursion formula, not the Heron/Babylonian formula that got from somewhere else.




回答2:


According to the algorithm you presented for the square root, you can try the code below

function [sqa, n] = mySqrt(a)
n = 2; % start from 2
X = [1,a]; % initial value for sequence X
while true % repeat procedure until termination condition is reached
    X(n+1) = (a + (X(n)*X(n-1)))/(X(n)+X(n-1)); % update sequence X by assigning new values
    if abs(X(n+1)-X(n)) <= eps(10*a) % termination condition
      break;
    end
    n = n + 1;
end 
sqa = X(end); % return the last element of X as the square root
end

such that

>> [sqa,n] = mySqrt(a)
sqa =  321.00
n =  20


来源:https://stackoverflow.com/questions/60395762/error-in-code-a-method-to-compute-sqrt-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!