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!

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



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}]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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