Composite Trapezoid Rule: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
Line 5: Line 5:


function integral = trapezoidal(f, a, b, n)
function integral = trapezoidal(f, a, b, n)
h = (b-a)/n;
x = (b-a)/n;
result = 0.5*f(a) + 0.5*f(b);
result = 0.5*f(a) + 0.5*f(b);
for i = 1:(n-1)
for i = 1:(n-1)
result = result + f(a + i*h);
result = result + f(a + i*x);
end
end
integral = h*result;
integral = x*result;
end
end



Revision as of 13:55, 8 April 2018

In numerical analysis, the trapezoidal rule is used for approximation of a definite integral. The code here is a general purpose code for any equation.


MATLAB

function integral = trapezoidal(f, a, b, n)

   x = (b-a)/n;
   result = 0.5*f(a) + 0.5*f(b);
   for i = 1:(n-1)
       result = result + f(a + i*x);
   end
   integral = x*result;

end

f is the equation, a is the lower limit, b is the upper limit, and n is the number of trapezoids or number of integration points.