Re: Is this a bug?
- To: mathgroup at smc.vnet.net
- Subject: [mg32056] Re: [mg32047] Is this a bug?
- From: Andrzej Kozlowski <andrzej at tuins.ac.jp>
- Date: Fri, 21 Dec 2001 03:57:24 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
No, there is no bug here. If you think carefully about this you'll see that k[5] has two be evaluated twice 9at least!). Increment[a[k[5]] has to compute the value of a[0]=a[k[5]](first time) , add one to it and assign it to a[0]=a[k[5]] (second time) then return the old value. The last step does not require computing k[5] again because Increment remembers it. This saves you one evaluation of k[5] (and one "hallo world") compared with the following code which otherwise does the same thing: In[22]:= (a[k[5]]=a[k[5]]+1;a[k[5]]-1) In[22]:= hallo world hallo world hallo world Out[22]= 0 You see that this time "hallo world" was printed three times. The difference is that Increment remembers the "old value" so it does not need to compute it again. Andrzej Kozlowski Toyama International University JAPAN http://platon.c.u-tokyo.ac.jp/andrzej/ On Thursday, December 20, 2001, at 05:42 PM, Paul van Wamelen wrote: > Is the following a bug? > > Mathematica 4.1 for Sun Solaris > Copyright 1988-2000 Wolfram Research, Inc. > -- Motif graphics initialized -- > > In[1]:= k[x_] := Module[{},Print["hallo world"];x]; > > In[2]:= a[5] = 0; > > In[3]:= a[k[5]]++ > hallo world > hallo world > > Out[3]= 0 > > > I would have expected only one "hallo world" and it would seem to be > more efficient to only evaluate the k[5] once... > > The above example is not important but in the form below it had me > baffled for a while: > > In[4]:= tst[n_] := Module[{a}, > a[0] = a[1] = 0; > Do[a[Random[Integer,{0,1}]]++,{n}]; > {a[0],a[1]}] > > In[5]:= tst[50] > > Out[5]= {24, 24} > > (Does not add up to 50!) > > Thanks! > > > > >