Re: Workaround for an unexpected behavior of Sum
- To: mathgroup at smc.vnet.net
- Subject: [mg91078] Re: Workaround for an unexpected behavior of Sum
- From: magma <maderri2 at gmail.com>
- Date: Tue, 5 Aug 2008 04:04:19 -0400 (EDT)
- References: <g76aq6$dfs$1@smc.vnet.net>
On Aug 4, 9:23 am, "Jose Luis Gomez" <jose.luis.go... at itesm.mx> wrote: > 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 It is very kind of Jose to call this "odd behaviour", I would call it a serious bug. It means the that the iteration variables are not really localized, at least in some cases. WRI should correct it asap.