matlab - MATLAB:辛普森的 1/3 法则
问题描述
我已经为辛普森规则创建了一个代码,但我认为我的函数错了。我没有其他来源可以参考(或者它们太难理解了)。这是我的代码:
function s = simpson(f_str, a, b, h)
f = inline(f_str);
n = (b-a)/h;
x = a + [1:n-1]*h;
xi = a + [1:n]*h;
s = h/3 * (f(a) + f(b) + 2*sum(f(x)) + 4*sum(f(xi)));
end
谁能帮忙看看哪里错了?
解决方案
假设h
您的函数中的 是步长:
function s = simpson(f_str, a, b, h)
% The sample vector will be
xi = a:h:b;
f = inline(f_str);
% the function at the endpoints
fa = f(xi(1));
fb = f(xi(end));
% the even terms.. i.e. f(x2), f(x4), ...
feven = f(xi(3:2:end-2));
% similarly the odd terms.. i.e. f(x1), f(x3), ...
fodd = f(xi(2:2:end));
% Bringing everything together
s = h / 3 * (fa + 2 * sum(feven) + 4 * sum(fodd) + fb);
end
推荐阅读
- runge-kutta - 将 Runge-Kutta 时间方案应用于不可压缩求解器
- scala - 在 Docker 容器中运行 sbt
- angular - 组件子视图刷新子输出 - 不应该发生
- java - Spring Tests:为数据文件发送多部分
- sql - SQL - 如何重命名内部连接中使用的列
- python - 有没有办法在 selenium 中找到一个 xpath,看看它是否包含我想要的文本,然后找到前面的文本?
- java - 使用 IntStream 而不是流迭代两个列表列表
- python - Pyspark 函数本身可以正常工作,但在包装在 UDF 中时不执行任务
- javascript - JavaScript onclick 为什么说函数未定义?
- excel - 卡在 VBA 引用中