本文介绍了代码错误,一种计算sqrt的方法(a)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

X(n+1) = (a + (X(n)*X(n-1))/(X(n)+X(n-1)), n = 1, 2, …,

带有X0=1X1=a

(也就是说,已知lim n-> infin of Xn = sqrt(a)

with X0=1 and X1=a (That is, it is known that lim n-> infin of Xn = sqrt(a)

编写一个实现该计算的函数[sqa, nitr] = mySqrt(a).该函数应使用while循环,当Xn + 1和Xn之间的差变得小于eps(10*a)时终止,并在sqa中输出Xn + 1并在.测试a = 103041的功能.

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

我得到了错误:

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

有人可以帮我吗?

推荐答案

根据您提出的平方根算法,您可以尝试以下代码

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

如此

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

这篇关于代码错误,一种计算sqrt的方法(a)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 05:58