First coding of Composite Simpson's rule

f[x_] = Sin[x];
a = 1. ;
b = 3. ;
n = 22;
m = n/2;
h = (b - a)/n;
approx = 
      h/3*Sum[f[a + 2  k h] + 4  f[a + (2  k + 1) h] + 
            f[a + (2  k + 2) h], {k, 0, m - 1}]

exact = -Cos[3. ] + Cos[1. ]

approx - exact

Second coding of Composite Simpson's rule

f[x_] = Sin[x];
a = 1. ;
b = 3. ;
n = 22;
m = n/2;
h = (b - a)/n;
approx = 
      h/3*(f[a] + 4  Sum[f[a + k*h], {k, 1, n - 1, 2}] + 
            2  Sum[f[a + k*h], {k, 2, n - 2, 2}] + f[b])

exact = -Cos[3. ] + Cos[1. ]

approx - exact

Timing tests

We can use the Timing[] function to get a sense of how long each piece of code takes to execute.  You should read the documentation on this function.  First, let's set n to some big value and the recalculate values of m and h.

f[x_] = Sin[x];
a = 1. ;
b = 3. ;
n = 10^5;
m = n/2;
h = (b - a)/n;

The next input returns the time for our first coding.  You might want to run this several time to see the variation that occurs.

Timing[
      h/3*Sum[f[a + 2  k h] + 4  f[a + (2  k + 1) h] + 
            f[a + (2  k + 2) h], {k, 0, m - 1}]]

Here's the second coding.

Timing[
      h/3*(f[a] + 4  Sum[f[a + k*h], {k, 1, n - 1, 2}] + 
            2  Sum[f[a + k*h], {k, 2, n - 2, 2}] + f[b])]

Since there is variation from run to run, it might be useful to look at an average over more than one run.  The next input does so for the first coding using the Mean[] function.

Mean[
      Table[Timing[
          h/3*Sum[f[a + 2  k h] + 4  f[a + (2  k + 1) h] + 
                f[a + (2  k + 2) h], {k, 0, m - 1}]], {i, 1, 
          10}]]

Comare with the average for the second coding given next.

Mean[
      Table[Timing[
          h/3*(f[a] + 4  Sum[f[a + k*h], {k, 1, n - 1, 2}] + 
                2  Sum[f[a + k*h], {k, 2, n - 2, 2}] + f[b])], {i, 1, 
          10}]]