首页 > 解决方案 > 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

谁能帮忙看看哪里错了?

标签: matlabsimpsons-rule

解决方案


假设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

来源:
https ://en.wikipedia.org/wiki/Simpson%27s_rule


推荐阅读