yinitial = x
y_n接近sqrt(x)为n->无穷大
如果是x输入和tol输入。只要| y ^ 2-x | > tol为真计算y = 0.5 *(y + x / y)的以下等式。我将如何创建一个在| y ^ 2-x |时停止的while循环< = tol。所以每次循环时y值都会改变。为了得到这个答案--->
>>sqrtx = sqRoot(25,100)
sqrtx =
7.4615
到目前为止我写了这个:
function [sqrtx] = sqrRoot(x,tol)
n = 0;
x=0;%initialized variables
if x >=tol %skips all remaining code
return
end
while x <=tol
%code repeated during each loop
x = x+1 %counting code
end
答案 0 :(得分:4)
该公式使用Newton方法的修改版本来确定平方根。 y_n
是上一次迭代,y_{n+1}
是当前迭代。您只需要为每个变量保留两个变量,然后在满足容差标准时,返回当前迭代的输出。您也正在递增错误的值。它应该是n
,而不是x
。你也没有正确计算公差......更仔细地阅读问题。您获取当前迭代的输出,将其平方,用所需的值x
减去,取绝对值并查看输出是否小于容差。
此外,您需要确保公差小。将容差指定为100可能不允许算法迭代并为您提供正确的答案。看到收敛到正确答案需要多长时间也可能有用。因此,返回n
作为函数的第二个输出:
function [sqrtx,n] = sqrRoot(x,tol) %// Change
%// Counts total number of iterations
n = 0;
%// Initialize the previous and current value to the input
sqrtx = x;
sqrtx_prev = x;
%// Until the tolerance has been met...
while abs(sqrtx^2 - x) > tol
%// Compute the next guess of the square root
sqrtx = 0.5*(sqrtx_prev + (x/sqrtx_prev));
%// Increment the counter
n = n + 1;
%// Set for next iteration
sqrtx_prev = sqrtx;
end
现在,当我使用x=25
和tol=1e-10
运行此代码时,我明白了:
>> [sqrtx, n] = sqrRoot(25, 1e-10)
sqrtx =
5
n =
7
25的平方根是5 ...至少是那天我从数学课上记得的。它还需要7次迭代才能收敛。还不错。
答案 1 :(得分:2)
是的,这正是您应该做的事情:一遍又一遍地使用y_{n+1}
的等式。
在你的代码中,你应该有一个像
这样的循环while abs(y^2 - x) > tol
%// Calculate new y from the formula
end
另请注意,tol
应该很小,如另一个答案所述。参数tol
实际上告诉您您的解决方案有多么不准确。通常,您需要更准确或更不准确的解决方案,因此将tol
设置为接近零的值。
答案 2 :(得分:-1)
解决这个问题的正确方法..
function [sqrtx] = sqRoot(x,tol)
sqrtx = x;%output = x
而abs((sqrtx。^ 2) - x)&gt; tol%逻辑表达式来测试它应该
的时间端
sqrtx = 0.5 *((sqrtx)+(x / sqrtx)); %,而条件证明是真的计算
端
端