MATLAB:Simpson的1/3规则

时间:2018-05-23 04:39:33

标签: matlab simpsons-rule

我已经为辛普森的规则创建了一个代码,但我认为我的功能错了。我没有其他资料可供参考(或者他们很难被理解)。这是我的代码:

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

有人可以帮忙看看错误的部分在哪里吗?

1 个答案:

答案 0 :(得分:0)

假设您的函数中的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