       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 has two be evaluated twice 9at least!). Increment[a[k]  has
to compute the value of a=a[k](first time) , add one to it  and
assign it to a=a[k] (second time) then return the old value. The
last step does not require computing k again because  Increment
remembers it. This saves you one evaluation of k (and one "hallo
world") compared with the following code which otherwise does the same
thing:

In:=
(a[k]=a[k]+1;a[k]-1)

In:=
hallo world

hallo world

hallo world

Out=
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:= k[x_] := Module[{},Print["hallo world"];x];
>
> In:= a = 0;
>
> In:= a[k]++
> hallo world
> hallo world
>
> Out= 0
>
>
> I would have expected only one "hallo world" and it would seem to be
> more efficient to only evaluate the k once...
>
> The above example is not important but in the form below it had me
> baffled for a while:
>
> In:= tst[n_] := Module[{a},
>   a = a = 0;
>   Do[a[Random[Integer,{0,1}]]++,{n}];
>   {a,a}]
>
> In:= tst
>
> Out= {24, 24}
>
> (Does not add up to 50!)
>
> Thanks!
>
>
>
>
>

```

• Prev by Date: Re: Urgent Plot problem
• Next by Date: Re: Is this a bug?
• Previous by thread: Re: Is this a bug?
• Next by thread: Re: Is this a bug?