2
$\begingroup$

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.

$\endgroup$
4
$\begingroup$

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.

$\endgroup$
4
  • 1
    $\begingroup$ "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]]... $\endgroup$
    – J. M.'s torpor
    Oct 4 '12 at 9:32
  • $\begingroup$ @J.M. I think NSum[ ] is calling NIntegrate[] try for example NSum[1/k^2, {k, 1, 10^100}] $\endgroup$ Oct 4 '12 at 15:35
  • $\begingroup$ @bel, that too (well, either of Integrate[] or NIntegrate[]); NSum[]'s default method is Euler-Maclaurin, which does involve the integration of the summand... $\endgroup$
    – J. M.'s torpor
    Oct 4 '12 at 15:40
  • $\begingroup$ @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… $\endgroup$
    – xzczd
    Oct 5 '12 at 2:40
0
$\begingroup$

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}]
$\endgroup$
1
  • $\begingroup$ Um… “a function as its first argument”,…not exactly, I think. Part is also a function, right? $\endgroup$
    – xzczd
    Oct 5 '12 at 2:30

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.