# Is it possible to compute with the trapezoidal rule by numerical integration?

Is it possible to compute trapezoidal rule numerical integration? I know that Mathematica has Interpolation, and that a list of points can be interpolated and then integrated simply using Integrate. However, my functions are highly oscillatory (they are based on simulation data), and I am not convinced that the interpolation is perfect, even when I set WorkingPrecision to a very high value. Also, I know that ListIntegrate is deprecated, and even if I use it, I am not certain if it is using the trapezoidal rule, which I would like to use.

Do you know if any resources where I can find Mathematica or pseudocode for trapezoidal integration of lists of points? Or do you have any suggestions about how I can use Mathematica efficiently to program such an algorithm myself?

Thanks!

• Why not start at the obvious place: en.wikipedia.org/wiki/Trapezoidal_rule – rm -rf May 16 '12 at 15:51
• Actually NIntegrate[] indeed is able to perform the trapezoidal rule (see docs for details). I suspect that it won't be the best method for your problem; why not elaborate a bit more on these oscillatory functions you speak of? – J. M. is away May 16 '12 at 15:53
• Might check Documentation Center > Integrationtutorial/NIntegrateIntegrationStrategies#144042466 and tutorial/NIntegrateIntegrationRules#32844337 for some ideas on option setting for NIntegrate of finite region oscillatory functions. – Daniel Lichtblau May 16 '12 at 17:04

t = Table[{x, Sin[x]}, {x, 0, Pi, .01}];
1/2 Total[((#[[2, 1]] - #[[1, 1]]) (#[[2, 2]] + #[[1, 2]])) & /@  Partition[t, 2, 1]]
(*
-> 1.99998
*)


Perhaps better

1/2 Total[Differences[t[[All, 1]]] ListCorrelate[{1, 1}, t[[All, 2]]]]


They are just

$$\int_a^b f(x)\,dx\approx\frac12\sum_{k=1}^N (x_{k+1}-x_k)(f(x_{k+1})+f(x_k))$$

Edit

Just for fun, using JM's shorter expression:

Manipulate[
Column[{
Show[Plot[Sin[x], {x, 0, Pi}], ListLinePlot[#, Filling -> Axis],
AspectRatio -> Automatic, ImageSize -> 400],
Row[{"Approx Integral = ",N@Differences[#1].MovingAverage[#2, 2]& @@ Transpose[#]}]}]&@
Table[{x, Sin[x]}, {x, 0, Pi, Pi/a}],
{{a, 2, Dynamic[a]}, 2, 10, 1}]


• Another possibility: Differences[#1].MovingAverage[#2, 2] & @@ Transpose[t]. – J. M. is away May 16 '12 at 16:16
• In your example using ListCorrelate I'd use Differences[...].ListCorrelate[...]/2 instead of Total[Differences[...] ListCorrelate[...]]/2 as the intent is clearer. – rcollyer May 17 '12 at 13:15
• @rcollyer I was just showing off my knowledge of commutativity :). Anyway, I think J. M.'s MovingAverage[] is better, so I used it in the Manipulate example. And yes, Dot[] is better than Total[] here. – Dr. belisarius May 17 '12 at 13:23
• MovingAverage is definitely superior. – rcollyer May 17 '12 at 13:30

The Wolfram Demonstrations Project has this demo. It might provide an idea or two to help.