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.
– aaaaa Sep 29 '16 at 02:02Tn[f_, a_, b_, n_] := ((b - a)/2 n)*(f[a] + f[b] +Sum[2 f[a + ((i (b - a))/n)], {i, 1, n - 1}])1/2 nis0.5 n; should be1/(2 n). – corey979 Sep 29 '16 at 02:10Tnis provided in my answer.Tn[2 #^3 &, 0, 1, 2]yields0.625. Correcting your2 nto(2 n)gives the same result. I don't understand what you are doing. – corey979 Sep 29 '16 at 02:24