# Creating my own midpoint rule function in Mathematica

I'm building my own function that is basically a midpoint riemann sum, but I cannot seem to get it to work.

Currently I have

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


I know it is wrong but I cannot figure out how to fix it. I know that when "I" reaches "n" number, the function will calculate for f[N+1] which is not what I want, but I cant figure out how to fix it. Any help would be appreciated!

• change {i, 0, n} to {i, 0, n-1}? – kglr Nov 29 '17 at 3:12
• It still gives me the wrong answer unfortunately but I think that is part of the solution. – John Nov 29 '17 at 3:18
• Is f[i] defined? Please give full code. – David G. Stork Nov 29 '17 at 3:41
• I was using f[x_] := Sin[x] just to check my answer. There is no other code for this. – John Nov 29 '17 at 3:46

You have to evaluate f at the right quadrature points. This can be done, e.g. as follows:

Mid[f_, a_, b_, n_] := With[{h = N[((b - a)/n)]},
0.5 h Sum[f[t] + f[t + h], {t, a, b - h, h}]
]


Here is a test:

f = Sin;
Mid[f, 0, 1, 200]
NIntegrate[f[t], {t, 0, 1}]


0.459697

0.459698

Note that this way, the function f gets evaluated twice for each interior quadrature point, so basically, twice as often as necessary. So, this is something that might be improved upon, e.g. like this

Mid2[f_, a_, b_, n_] :=  With[{h = N[((b - a)/n)]},
0.5 h (f[a] + f[b]) + h Sum[f[t], {t, a + h, b - h, h}]
]