Pergunta

I have tried, just for the fun of it, to write a MatLab-code for the composite Simpson's rule. As far as I can see, the code is correct, but my answers are not as accurate as I would like. If I try my code on the function f = cos(x) + e^(x^2), with a = 0, b = 1 and n = 7, my answer is roughly 1,9, when it should be 2,3. If I use the algorithm available at Wikipedia, I get a very close approximation with n = 7, so my code is obviously not good enough. If someone can see any mistakes in my code, I would really appreciate it!

function x = compsimp(a,b,n,f)
% The function implements the composite Simpson's rule

h = (b-a)/n;
x = zeros(1,n+1);
x(1) = a;
x(n+1) = b;
p = 0;
q = 0;

% Define the x-vector
for i = 2:n
    x(i) = a + (i-1)*h;
end

% Define the terms to be multiplied by 4
for i = 2:((n+1)/2)
    p = p + (f(x(2*i -2)));
end

% Define the terms to be multiplied by 2
for i = 2:((n-1)/2)
    q = q + (f(x(2*i -1)));
end

% Calculate final output
x = (h/3)*(f(a) + 2*q + 4*p + f(b));
Foi útil?

Solução

Your interval [a,b] should be split into n intervals. This results in n+1 values for x that form the boundary of each partition. Your vector x contains only n elements. It appears that your code is only dealing with n terms instead of n+1 as required.

EDIT:: Now you have modified the question based on the above, try this

% The 2 factor terms
for i = 2:(((n+1)/2) - 1 )
    q = q + (f(x(2*i)));
end

% The 4 factor terms
for i = 2:((n+1)/2)
   p = p + (f(x(2*i -1)));
end

Outras dicas

The code you have created works just fine. The only problem I see is n. From my experience, try n>=10000 for any function.

function x = compsimp(a,b,n,f)

I don't know if this matters but shouldn't be f the first letter:

function x = compsimp(f,a,b,n)

The correction should be in the parts p1, p2 and p3. I tried it and got approximately exact results:

enter image description here

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top