I encountered this problem and was unpleasantly surprised. Let us define a function:


k is supposed to be a dummy variable, right?

Let us calculate g[x+t], you get 1+t+x+(t+x)^2, all good.

Now g[x+k] gives 2+x+(x+2)^2... Really?!

So you should remember all summation variables used in functions and never use them as external variables. I encountered this problem and couldn't understand why it is giving the wrong answer. Looks like a bug to me.

  • $\begingroup$ How about Module? $\endgroup$ – Αλέξανδρος Ζεγγ Nov 30 '18 at 1:20
  • $\begingroup$ You can use Module and add "k" to local variables. Then it works. However, I thought that summation variables should be dummy without declaration. I thought wrong. $\endgroup$ – Aus Man Nov 30 '18 at 1:34
  • 2
    $\begingroup$ In the Details and Options the current documentation for Sum says "The iteration variable i is treated as local, effectively using Block." I am guessing the evaluation details of SetDelayed are interacting with the evaluation details of Sum. Now and then I wish there was a brilliantly clear text on nothing but the evaluation process within Mathematica. I suspect really deeply understanding that would take anyone's skill to the next level. $\endgroup$ – Bill Nov 30 '18 at 2:52
  • $\begingroup$ This happens because function evaluation in Mathematica should be seen as a code-rewriting operation. Whenever you evaluate a function defined with :=, Mathematica essentially inserts returns the body of the function with the argument slots replaced with the function arguments you called the function with. $\endgroup$ – Sjoerd Smit Nov 30 '18 at 9:27
  • $\begingroup$ @SjoerdSmit I think many users learn early on "it is all code rewriting" but I think the deep implications of that are what escape many users. If you watch the posts then again and again you see "you need an Evaluate inside Plot when the user doesn't understand why and most of the time you don't. Likewise RuleDelayed in replacement patterns. Software is built on making the surface structure look one way but being completely different below the surface. Has Shifrin or anyone else written that brilliant clear text on nothing but the evaluation process to take everyone to the next level? $\endgroup$ – Bill Nov 30 '18 at 16:56
g[x_] := Module[{k}, Sum[x^k, {k, 0, 2}]]

{g[x], g[x + t], g[x + k]}

{1 + x + x^2, 1 + t + x + (t + x)^2, 1 + k + x + (k + x)}

Same issue with Table and Do:

ClearAll[h1, h2]
h1[x_] := Table[x^k, {k, 0, 2}]
h1[x + k]

{1, 1 + x, (2 + x)^2}

h2[x_] := (zz = {}; Do[AppendTo[zz, x^k], {k, 0, 2}]; Total@zz)
h2[x + k]

2 + x + (2 + x)^2

| improve this answer | |
  • $\begingroup$ And Integrate, I think! $\endgroup$ – march Nov 30 '18 at 5:48

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.