2
$\begingroup$

Why does adding two elements from a list as follows:

test = {1, 2};
NSum[test[[n]], {n, 1, 2}]

lead to the warning "The expression n cannot be used as a part specification."? It does produce the correct answer but I don't know how to get rid of the warning.

$\endgroup$
2
  • 1
    $\begingroup$ Any reason you want to use NSum for this instead of Total? $\endgroup$ Commented Nov 1, 2022 at 14:19
  • $\begingroup$ I'm wanting to sum only certain elements of a much bigger list. The example above is merely a simple demonstration of the error I was getting. $\endgroup$
    – Chris
    Commented Nov 1, 2022 at 18:41

1 Answer 1

5
$\begingroup$

I suspect the reason for the warning is because:

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

NSum has attribute HoldAll, and effectively uses Block to localize variables.

So under the hood it is doing something like

Clear[n]
{1, 2}[[n]] (* triggers your error *)

n = 1;
{1, 2}[[n]] (* produces your answer *)

To get rid of the warning does this work for you?

test = {1, 2};
NSum[Indexed[test, n], {n, 1, 2}] (*3.*)
$\endgroup$
2
  • $\begingroup$ PS: the notes on NSum are from the documentation $\endgroup$ Commented Nov 1, 2022 at 17:15
  • 1
    $\begingroup$ Thanks. That did indeed remove the error. $\endgroup$
    – Chris
    Commented Nov 1, 2022 at 18:40

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.