在matlab中重写梯形到simpson规则

时间:2018-05-01 20:30:08

标签: matlab simpsons-rule

我正在尝试编写一个matlab程序,通过梯形和辛普森统计来计算积分。梯形程序如下:

    function [int, flag, stats] = trapComp(f, a, b, tol, hMin)
        % Initialise variables
        h = b - a;
        n = 1;
        int = h / 2 * (f(a) + f(b));
        flag = 1;

        if nargout == 3
            stats = struct('totalErEst', [], 'totalNrIntervals', [], 'nodesList', []);
        end

        while h > hMin
            h = h / 2;
            n = 2 * n;
            if h < eps % Check if h is not "zero"
                break;
            end

            % Update the integral with the new nodes
            intNew = int / 2;
            for j = 1 : 2 : n
                intNew = intNew + h * f(a + j * h);
            end

            % Estimate the error
            errorEst = 1 / 3 * (int - intNew);
            int = intNew;
            if nargout == 3 % Update stats
                stats.totalErEst = [stats.totalErEst; abs(errorEst)];
                stats.totalNrIntervals = [stats.totalNrIntervals; n / 2];
            end

            if abs(errorEst) < tol
                flag = 0;
                break
            end
        end
    end

现在辛普森统治我真的不能解决。我知道它非常相似,但我似乎无法弄明白。

这是我的辛普森代码:

function [int, flag, stats] = simpComp(f, a, b, tol, hMin)
    % Initialise variables
    h = b - a;
    n = 1;
    int = h / 3 * (f(a) + 4 * f((a+b)/2) + f(b));
    flag = 1;

    if nargout == 3
        stats = struct('totalErEst', [], 'totalNrIntervals', [], 'nodesList', []);
    end

    while h > hMin
        h = h / 2;
        n = 2 * n;
        if h < eps % Check if h is not "zero"
            break;
        end

        % Update the integral with the new nodes
        intNew = int / 2;
        for j = 1 : 2 : n
            intNew = intNew + h * f(a + j * h);
        end

        % Estimate the error
        errorEst = 1 / 3 * (int - intNew);
        int = intNew;
        if nargout == 3 % Update stats
            stats.totalErEst = [stats.totalErEst; abs(errorEst)];
            stats.totalNrIntervals = [stats.totalNrIntervals; n / 2];
        end

        if abs(errorEst) < tol
            flag = 0;
            break
        end
    end
end

然而,使用它可以得到一个误差大于梯形的积分的答案,我认为它不应该。

任何帮助将不胜感激

0 个答案:

没有答案