I'm working on a Mathematica lab for Calc. 2, and I ran into a problem last night. I was trying to calculate the midpoint approximation of the definite integral of Cos[x] from 0 to 2. Here's what I came up with:
Clear[a, b, n, f] f[x_] = Cos[x] a := 0; b := 2; n := 578 N[((b - a)/n)*Sum[f[a + (i - (1/2))*((b - a)/n)], {i, 1, n}]] 0.909298 This is fine, but if I try to use NSum instead of N[...Sum[...]] then this happens:
Clear[a, b, n] a := 0; b := 2; n := 578 ((b - a)/n)*NSum[f[a + (i - (1/2))*((b - a)/n)], {i, 1, n}] During evaluation of In[35]:= SequenceLimit::seqlim: The general form of the sequence could not be determined, and the result may be incorrect. >>
During evaluation of In[35]:= SequenceLimit::seqlim: The general form of the sequence could not be determined, and the result may be incorrect. >>
35.538
According to the documentation, Sum evaluates the given sum (http://reference.wolfram.com/mathematica/ref/Sum.html), and the N function gives the numerical value of the parameter (http://reference.wolfram.com/mathematica/ref/N.html). Also, NSum should give the numerical approximation of the sum. To my understanding, N[Sum[...]] Should be the same as NSum[...], or am I missing something?
It's not a huge deal as far as typing more, but I'd just like to know why it doesn't work as expected. I've read online that NSum apparently tries to work out part of the sum symbolically, but even if it does I don't see how it could be THAT much different from the real answer.
((b - a)/n)*Sum[f[a + (i - (1/2))*((b - a)/n)], {i, 1, n}] // Nworks. $\endgroup$n < 159. Once n gets any bigger you get those warnings and the values get sporadic. $\endgroup$((b - a)/n)* NSum[f[a + (i - (1/2))*((b - a)/n)], {i, 1, n}, NSumTerms -> 1000]$\endgroup$N[Sum[...]]computes the sum exactly and then converts it to floating point output, whereasNSum[...]attempts, through various numerical mechanisms, to approximate the sum (and might not even actually calculate all the terms in the sum in doing so). As the help notes, it can be fooled and needs judicious application of appropriate options to work well. It sounds like you are attempting to useNSum[...]where you really want something likeTotal@N@Table[...], especially if you're experimenting with Riemann integration. $\endgroup$Total@Table[]. $\endgroup$