Question: Composite Trapezoidal and Simpson's 1/3 Procedure Help

I am attempting to write a procedure for the numerical integration methods of the composite trapezoidal rule and Simpson's 1/3 rule, however the results that are being produced when I try to test the procedure are differing to the computed integral using the int command.

Here is my attempt so far:

 

> f:= x -> cos(x)*exp(-x/4):


> CompTrap:= proc(f,a,b,n)
local i, aa, h;
h:= (b-a)/n;
aa:= f(a)+f(b);

for i from 1 to n by 1 do

aa:= aa + 2*(f(a+(i*h)));
end do;
aa:= aa*0.5*h;
return aa;
end proc:

> Comp_Simp_1_3:= proc(f,a,b,j)
local i, aa, h;
h:= (b-a)/2;
aa:= f(a)-f(b);

for i from 1 to j by 1 do

aa:= aa + 4*f(a(2*i-1)*h) + 2*f(a(2*i)*h);
end do;
aa:= aa*(1/3)*h;
return aa;
end proc:

These are my two procedures, I have then calculated the result for a=1, b=8, n=4:

> evalf(int(cos(x)*(exp(-x/4)), x=8..1));
0.3871279027


> evalf(CompTrap(f,1,8,4));
-0.2499889420


> evalf(Comp_Simp_1_3(f,1,8,4));
-10.41655799

 

Could anybody suggest why the results are coming out as they are? I assume there are errors in my procedure code but I'm having a hard time trying to correct it.

Thank you,

P



Please Wait...