matlab - 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
解决方案
我想你可以试试下面的代码。
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
推荐阅读
- azure - Azure 登录到多租户 AD 应用程序失败
- javascript - 如何使用 react-router-dom 重定向到一个全新的 URL?
- github - 恢复已删除的存储库 github 企业
- javascript - 替换数组中的数据
- windows - 在批处理文件中创建看门狗并在启动时运行它
- c++ - 无法找到简单的 switch case 枚举错误
- r - 仅使用 ifelse 舍入数值变量
- android - Android listFiles 返回空数组
- jquery - 2 select2 在一个表单中,一个添加了最大选择值
- null - Google Data Studio 显示“null”——如何设置字段值?