MathGroup Archive 2005

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: For Loop and Array related


On Jun 15, 2005, at 5:58 AM, mchangun at gmail.com wrote:

> Hi All,
>
> I have an array with 100 elements, all set to zero initially.  Then I
> want to randomly choose one element and increase its value by one, and
> repeat this 16000 times. Here is my code:
>
> Lattice = Table[0, {n, 100}];
> For[i = 1, i = 16000, i++, Lattice[[Random[Integer, {1, 100}]]]++]
>
> So now if I add all the elements in the list Lattice together, I  
> should
> get 16000 (I use Total[Lattice] to get the sum of the list).  But this
> doesn't happen, and strangely, each time I run this, the sum of the
> list is different!  What am I doing wrong?
>
> Also I'm aware that a lot of Mathematica newbies try and write code
> like it were C++ and I think i've fallen into this trap as well.   
> So is
> there a different (more Mathematica) way which I can implement the
> above?
>
> Thanks in advanced.
>

Looks to me that the Increment operator has problems here.  I  
modified your program for a While.

In[152]:=
i = 0;
n = 100;
s = 160;
lattice = Table[0, {j, n}];
While[i++ <= s,
    lattice[[Random[Integer,
        {1, 100}]]]++;
     Print[i]; Print[
      Total[lattice]];
     Print[Tr[lattice]];
     Print[Sum[lattice[[k]],
       {k, 1, n}]];
     Print[i - Tr[lattice]];
     Print["-----"]; ];

When I run this, the Total, Tr and Sum all agree.  However Print[i -  
Tr[lattice]]; clearly show that sometimes no increment takes place  
and sometimes it is incremented with more than just one.


If I re-write the

lattice[[Random[Integer,
        {1, 100}]]]++;

the old fashion way:

r = Random[Integer, {1, 100}];
lr = lattice[[r]];
lr = lr + 1;
lattice[[r]] = lr;

than it works fine.

János

In[171]:=
$Version
Out[171]=
"5.1 for Mac OS X (October \
25, 2004)"


--------------------------------------------
f @@ # & /@ ===  f @@@


  • Prev by Date: Re: For Loop and Array related
  • Next by Date: Re: splitting sublists
  • Previous by thread: Re: For Loop and Array related
  • Next by thread: Re: For Loop and Array related