首页 > 解决方案 > matlab 代码中关于函数的可能错误

问题描述

设 Sn = 8Σ (1/((4κ-3)(4κ-1)))。已知当 n 趋于不定式时,Sn 的 lim 等于 pi。编写一个函数 [sn,n] = mySumPi(tol) 输出 Sn 和 n 为最小的 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

标签: matlabsum

解决方案


我想你可以试试下面的代码。

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

推荐阅读