Workaround for an unexpected behavior of Sum
- To: mathgroup at smc.vnet.net
- Subject: [mg91036] Workaround for an unexpected behavior of Sum
- From: "Jose Luis Gomez" <jose.luis.gomez at itesm.mx>
- Date: Mon, 4 Aug 2008 03:23:54 -0400 (EDT)
Workaround for an unexpected behavior of Sum Let me describe the problem, before describing the solution (workaround) that I found. First: Next calculation works fine for me: j = 7; Sum[j^2, {j, 1, n}] Mathematica gave the answer I was expecting (n*(1 + n)*(1 + 2*n))/6, It means the global j and the dummy index j are actually different That is o.k., that is what I was expecting HOWEVER Next calculation gives an unexpected answer: Clear[f]; j = 7; Sum[f[j], {j, 1, n}] Now Mathematica answers n*f[7]. That is NOT what I was expecting I was expecting that Mathematica will return the Sum unevaluated, Sum[f[j], {j, 1, n}], and also with j unevaluated, so that the global j and the dummy index j remain different. NOW MY WORKAROUND FOR THIS "PROBLEM": AUTOMATICALLY CREATE A NEW DUMMY INDEX IF THERE EXISTS A VARIABLE WITH THE SAME NAME AS THE DUMMY INDEX. Evaluate this in your Mathematica session: Unprotect[Sum]; Sum[sumando_, before___, {dummyindex_, rest___}, after___] := ReleaseHold[ Hold[Sum[sumando, before, {dummyindex, rest}, after]] /. HoldPattern[dummyindex] :> Evaluate[ Unique[ToString[Unevaluated[dummyindex]]]]] /; (dummyindex =!= Unevaluated[dummyindex]); Protect[Sum]; Now, after the evaluation of the previous code, Mathematica behaves the way I was expecting: Clear[f]; j = 7; Sum[f[j], {j, 1, n}] This time Mathematica answers Sum[f[j1],{j1,1,n}]. The price we have to pay is that the dummy index was renamed. But it is a DUMMY INDEX, it can have any name. And the code makes the new name totally new, thanks to the Unique[] command. AFAIK this code does Not affect the answers of Sum in other cases. I hope this simple solution is somehow useful. Notice that the command Integrate has a similar (in my opinion odd) behavior, mixing dummy integration variables with global variables when the definite integral cannot be immediately performed. Best regards! Jose Luis Gomez-Munoz Mexico
- Follow-Ups:
- Re: Workaround for an unexpected behavior of Sum
- From: Andrzej Kozlowski <akoz@mimuw.edu.pl>
- Re: Workaround for an unexpected behavior of Sum