# Creating my own function to integrate by the trapezoidal rule [duplicate]

I'm trying to write a custom function that takes a definite integral and approximates the value using the trapezoidal rule. As can be seen in the code below, I first did this by defining all the variables separately:

f[x_] = 2 x^3;
a = 0;
b = 1;
n = 2;
Δx = (b - a)/n;
x[i_] = a + i*Δx;
Sum[(f[a] + 2 f[x[i]] + f[b])*.5 Δx, {i, 1, n - 1}];


Then, I tried putting all of this into a single function. Substituting out f[x[i]] and Deltax for what it is they represent:

Tn[f_, a_, b_, n_] :=
Sum[(f[a] + 2 f[a + i ((b - a)/n)] + f[b])*.5 ((b - a)/n), {i, 1, n - 1}]


I got this to work with the function I first tested, 2 x^3 at 2 intervals, but the results for other tests I did were vastly overestimated, so clearly that was just dumb luck and I have an issue in my code somewhere. Any help in this matter would be appreciated.

Your trapezoidal sum is simply wrong; compare carefully with, e.g., wikipedia.

$$\sum\limits_{i=1}^{n-1}\frac{b-a}{2n}\left[f(a)+2f\left(a+\frac{i(b-a)}{n}\right)+f(b)\right]$$

where $\frac{b-a}{2n}$ can be taken out of the sum as it doesn't contain the iterator $i$. Note that then $f(a)$ and $f(b)$ are summed $(n-1)$ times, so the $sum\,of\,2\,f(...)$ is increased by $(n-1)[f(a)+f(b)]$, hence the overestimation.

The correct form is

$$\frac{b-a}{2n}\left[f(a)+f(b)+\sum\limits_{i=1}^{n-1}2f\left(a+\frac{i(b-a)}{n}\right) \right]$$

where you don't take $(n-1)$ times $f(a)+f(b)$, but only once:

Tn[f_, a_, b_, n_] := 0.5*((b - a)/n)*
(f[a] + f[b] + Sum[2*f[a + (i*(b - a))/n], {i, 1, n - 1}])


gives

Tn[2 #^3 &, 0, 1, 20]


0.50125

Compare with exact result:

Integrate[2 x^3, {x, 0, 1}]


1/2

• I tried that, but I'm getting 2.5 instead of the expected estimation of .625 with two intervals Tn[f_, a_, b_, n_] := ((b - a)/2 n)*(f[a] + f[b] +Sum[2 f[a + ((i (b - a))/n)], {i, 1, n - 1}]) – aaaaa Sep 29 '16 at 2:02
• Because 1/2 n is 0.5 n; should be 1/(2 n). – corey979 Sep 29 '16 at 2:10
• Substituting ((b-a)/(2n)) for ((b-a)/2n) nets the sameresult, I don't believe it is that. – aaaaa Sep 29 '16 at 2:16
• The correct Tn is provided in my answer. Tn[2 #^3 &, 0, 1, 2] yields 0.625. Correcting your 2 n to (2 n) gives the same result. I don't understand what you are doing. – corey979 Sep 29 '16 at 2:24
• Hard-resetting the notebook seems to have done it, nevermind. Thank you for the assistance. – aaaaa Sep 29 '16 at 2:41