4
$\begingroup$

The below gives the right answer for summing values from a list (as opposed to a mathematical function) but throws out a warning stating that "k cannot be used for list specification".

list = {1, 2, 3, 4, 5};
NSum[list[[k]], {k, 1, 4}]

Why does it work at all then, and what's the right way to do it?

$\endgroup$
6
  • $\begingroup$ Use Sum rather than NSum: Sum[list[[k]], {k, 1, 4}]; or list // Most // Total $\endgroup$
    – Bob Hanlon
    Dec 3, 2017 at 22:00
  • $\begingroup$ Ah I knew I should have specified more ... I need NSum because I want to use WynnExtrapolation as Method, which Sum does not support. $\endgroup$
    – MvP
    Dec 3, 2017 at 22:17
  • 1
    $\begingroup$ Please provide a minimal example of where WynnExtrapolation is required. $\endgroup$
    – Bob Hanlon
    Dec 3, 2017 at 22:21
  • $\begingroup$ I think the precise question is: is there no way to get NSum to work on a list? The MWE list of coefficients I have in mind is list = Table[ SeriesCoefficient[Series[BesselJ[0, t]^2, {t, 0, 10}], k], {k, 0, 10, 2}] $\endgroup$
    – MvP
    Dec 3, 2017 at 22:45
  • 1
    $\begingroup$ NSum worked with the List, it just gave a warning (which can be suppressed by Quiet or turning Off the specific message). $\endgroup$
    – Bob Hanlon
    Dec 3, 2017 at 23:20

3 Answers 3

6
$\begingroup$

Adapted from the docs for NSum:

f[n_] := Exp[-1/(n + 1)];
list = Table[If[n == 1, f[1], f[n] - f[n - 1]], {n, 1., 10^5}];
ff[n_Integer] := list[[n]];

NSum[ff[n], {n, 1, ∞}, Method -> "WynnEpsilon"]
(*  1.00008  *)
$\endgroup$
1
  • 1
    $\begingroup$ Note: The OP's NSum[list[[n]], {n, 1, \[Infinity]}, Method -> "WynnEpsilon"] works, but slowly, because, I suspect, the list is copied multiple times. There is no such problem with ff[n]. $\endgroup$
    – Michael E2
    Dec 4, 2017 at 0:25
2
$\begingroup$

From the "Details" section of NSum:

NSum first localizes the values of all variables, then evaluates f with the variables being symbolic, and then repeatedly evaluates the result numerically.

So basically (if I'm understanding this correctly), NSum is trying to evaluate list[[k]] (with k as a symbol) at some point, which is why the message appears.

A better way to do it is as @Bob Hanlon commented:

Sum[list[[k]], {k, 1, 4}];

or:

list // Most // Total
$\endgroup$
2
$\begingroup$

The interpretation given by Anne is correct, you can reproduce the error message simply by evaluating

list[[k]]

During evaluation of In[5]:= Part::pkspec1: The expression k cannot be used as a part specification.

{1, 2, 3, 4, 5}[[k]]

One workaround is to use Indexed instead of Part:

NSum[Indexed[list, k], {k, 1, 4}]
10.
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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