matlab中关于函数的代码中可能存在错误



设Sn=8∑(1/((4κ-3((4κ-1((。已知当n趋向于不定式时,Sn的lim等于pi。编写函数[sn,n]=mySumPi(tol(,该函数输出最小n的sn和n,使得sn的绝对值pi

我已经编写了以下代码,但它似乎不起作用。

function [sn,n] = mySumPi(tol)
%[sn,n] = mySumPi(tol)
%lim as n approaches infinity is pi
% n is the smallest numbers such that the abs(sn-pi) <tol
count = 0;
sn=0
while abs(sn-pi) >= tol
sn = sn + (8*sn)*(((4*n)-3)*((4*n)-1)) 
count = count+1;
n = count - 1;   
end
end

我认为您可以尝试下面的代码。

function [sn,n] = mySumPi(tol)
n = 1; 
sn = 0;
while 1 % repeat the procedure until the termination condition is valid
sn = sn + 8/(((4*n)-3)*((4*n)-1)); % you had wrong formula in you code
if abs(sn-pi) < tol % termination condition
break;
else
n = n + 1;
end
end
end

使得

>> [sn,n] = mySumPi(1e-1)
sn =  3.0418
n =  5
>> [sn,n] = mySumPi(1e-3)
sn =  3.1406
n =  500
>> [sn,n] = mySumPi(1e-5)
sn =  3.1416
n =  50000

相关内容

  • 没有找到相关文章

最新更新