5
$\begingroup$

Why does this code produce a number close to 1000 but not exactly 1000?

a = {0, 0};
Do[a[[RandomChoice[{1, 2}]]]++, 1000]
Total[a]

Moreover the number seems to be random within some range.

$\endgroup$
3
  • 1
    $\begingroup$ related: 2300 $\endgroup$
    – Kuba
    Jan 12, 2017 at 12:36
  • $\begingroup$ @Kuba I had forgotten about that old question. Amusing that a search turned that up but not the newer one. I remember that at that time I was mightily confused until I figured it out so I posted the question to get others to consider the problem. $\endgroup$
    – Mr.Wizard
    Jan 12, 2017 at 13:02
  • 1
    $\begingroup$ @Mr.Wizard I forced myself to answer to be sure I got that :) Wasn't obvious the more that without TraceInternal one will not see the second RandomChoice. $\endgroup$
    – Kuba
    Jan 12, 2017 at 13:03

1 Answer 1

4
$\begingroup$

Because Increment is HoldAll and RandomChoice evaluates twice. First time to get the value to increment and the second time to pick the index that should be affected.

If both choices match then we are fine, otherwise we are speeding up or slowing down a little. E.g.: a = {3,4}, first RandomChoice is 1 and the second 2, then we take 3+1 and assign it in the second position which was 4 too. No change here. Reversely we would have 4+1 assigned for 3 so increment of 2!

You can use Trace

Trace[
  a[[RandomChoice[{1, 2}]]]++,
  TraceInternal -> True
] // Column

or manually check it:

a = {0, 0}
a[[Echo@RandomChoice[{1, 2}]]]++;
a

>>1

>>2

{0,1}

Twice indeed. (use (Print[#];#)& for pre V11).

To avoid that assign RandomChoice result somewhere (var=RandomChoice[...]) or e.g:

a = {0, 0};
Do[ a[[#]]++ &@RandomChoice[{1, 2}], 100]
Total[a]

100

$\endgroup$
2
  • $\begingroup$ Kuba, I marked this question as a duplicate. Please let me know if you disagree. $\endgroup$
    – Mr.Wizard
    Jan 12, 2017 at 12:55
  • $\begingroup$ @Mr.Wizard I don't :) I failed to find it though I wasn't sure if it was an exact duplicate. $\endgroup$
    – Kuba
    Jan 12, 2017 at 12:56

Not the answer you're looking for? Browse other questions tagged or ask your own question.