Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

I know what I'm doing can be done with Total:

a = Range@3;
Total@a

And if I simply choose Sum, nothing wrong will happen:

a = Range@3;
Sum[a[[i]], {i, 3}]

N@Sum is still OK:

a = Range@3;
N@Sum[a[[i]], {i, 3}]

But when it's changed to NSum, a warning message comes out though I still get the correct result:

a = Range@3;
NSum[a[[i]], {i, 3}]

Part::pspec: Part specification i is neither an integer nor a list of integers.

I found if I add a Hold, I can avoid the warning:

a = Range@3;
NSum[Hold@a[[i]], {i, 3}]

But I still want to know the exact reason.

share|improve this question
add comment

2 Answers

up vote 3 down vote accepted

The first thing I assumed was that the Hold* attributes of the functions must be different, but they both have the attributes HoldAll.

On the other hand, the algorithms behind Sum and NSum are quite different. I certainly don't know all the details but we can examine what's going on with TracePrint.

a = {1, 2, 3};
TracePrint[NSum[a[[i]], {i, 3}], _Part]

(* Print result:
    a[[i]]
    {1,2,3}[[i]]
*)

Note that Part is called with a symbolic argument i. Now, let's do it with Sum.

a = {1, 2, 3};
TracePrint[Sum[a[[i]], {i, 3}], _Part]

(* Print result:
  a[[i]]
  {1,2,3}[[1]]

  a[[i]]
  {1,2,3}[[2]]

  a[[i]]
  {1,2,3}[[3]]
*)

I suspect that NSum is attempting to do some symbolic evaluations of the summand.

share|improve this answer
1  
"I suspect that NSum[] is attempting to do some symbolic evaluations of the summand." - looking at TracePrint[NSum[a[[k]], {k, 3}], TraceInternal -> True], it apparently does; it tries to compile a[[i]]... –  J. M. Oct 4 '12 at 9:32
    
@J.M. I think NSum[ ] is calling NIntegrate[] try for example NSum[1/k^2, {k, 1, 10^100}] –  belisarius Oct 4 '12 at 15:35
    
@bel, that too (well, either of Integrate[] or NIntegrate[]); NSum[]'s default method is Euler-Maclaurin, which does involve the integration of the summand... –  J. M. Oct 4 '12 at 15:40
    
@J.M. "TraceInternal"…it's another option that isn't described clearly in the help, right? And… oh, the output with it is so complex… –  xzczd Oct 5 '12 at 2:40
add comment

Another possibility is that NSum[ ] wants to have a function as its first argument (and not a list). So if we supply a function

 a[x_]:=x;

to mimic your Range command, and you can NSum without warning using

 NSum[a[i], {i, 3}]

or more concisely

 NSum[i, {i, 1, 3}]
share|improve this answer
    
Um… “a function as its first argument”,…not exactly, I think. Part is also a function, right? –  xzczd Oct 5 '12 at 2:30
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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