2
$\begingroup$

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.

$\endgroup$
3
$\begingroup$

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

Your formulation is

$$\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

$\endgroup$
  • $\begingroup$ 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}]) $\endgroup$ – aaaaa Sep 29 '16 at 2:02
  • $\begingroup$ Because 1/2 n is 0.5 n; should be 1/(2 n). $\endgroup$ – corey979 Sep 29 '16 at 2:10
  • $\begingroup$ Substituting ((b-a)/(2n)) for ((b-a)/2n) nets the sameresult, I don't believe it is that. $\endgroup$ – aaaaa Sep 29 '16 at 2:16
  • $\begingroup$ 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. $\endgroup$ – corey979 Sep 29 '16 at 2:24
  • $\begingroup$ Hard-resetting the notebook seems to have done it, nevermind. Thank you for the assistance. $\endgroup$ – aaaaa Sep 29 '16 at 2:41

Not the answer you're looking for? Browse other questions tagged or ask your own question.