Composite Trapezoid Rule: Difference between revisions

From Rosetta Code
Content added Content deleted
No edit summary
 
Line 1: Line 1:
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.
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.
[https://en.wikipedia.org/wiki/Trapezoidal_rule]




== MATLAB ==
== MATLAB ==


function integral = trapezoidal(f, a, b, n)
function integral = trapezoid(f, a, b, n)
x = (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);

Latest revision as of 13:56, 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. [1]


MATLAB

function integral = trapezoid(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.