Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I simulate a simple experiment, a coin flip. What I do is accumulate the mean of the results up to the i-th experiment. What I can't figure out is why the computed means do not asymptotically approach 1/2. What did I do wrong? The code:

n = 10^4;
c = Table[{i, RandomInteger[]}, {i, 1, n}];
s = 0;
m = {};
For[i = 1, i <= n, i++,
  s += c[[i, 2]];
  AppendTo[m, {i, N[s/i]}];
share|improve this question
This seems to be converging on 0.5 for me but your method is very inefficient. What are you seeing and why do you expect something else? – Mr.Wizard Jan 19 '13 at 10:32

It should converge to 1/2, I think you just need to try higher values for n. Which is probably slow with your current non-functional method. Here's a simpler (and faster, and more functional) way to do the same calculation:

n = 1000000;
means = N[Accumulate[RandomInteger[1, n]]]/Range[n];

Now you can see it converges to 1/2 as expected:

ListLinePlot[means[[;; ;; 100]], PlotRange -> {0.4, 0.6}, 
 Epilog -> {Red, Dashed, Line[{{0, 0.5}, {Length[means], 0.5}}]}]

Mathematica graphics

share|improve this answer
Your method is quick enough for Manipulate[ListLinePlot[N[Accumulate[RandomInteger[1, t]]]/Range[t], PlotRange -> {0, 1}, AxesOrigin -> {0, 0.5}], {t, 10, 2000, 5}] – cormullion Jan 19 '13 at 11:10
@cormullion try this: Manipulate[SeedRandom[seed]; ListLinePlot[N[Accumulate[RandomInteger[1, t]]]/Range[t], PlotRange -> {0, 1}, AxesOrigin -> {0, 0.5}], {t, 10, 2000, 5}, {seed, 1, 20, 1}] – Mr.Wizard Jan 19 '13 at 11:46
@Misery: That's like saying a race car is slow because I don't like switching gears. I use MMA for image processing/number crunching, and in my experience, it is a bit slower but far more productive than e.g. C. If you use it right. – nikie Jan 19 '13 at 14:29
@Misery: No, Mathematica does not "support only functional programming." It supports procedural programming, functional programming, pattern-matching/rule-replacement programming, array-based programming, etc. But as with any interpreted language, the more that can be left to the system to do the better; which is why functional programming can so often be more efficient than procedural programming. Once you "speak" functional programming, you'll like it: it's often much easier to read than procedural programming. Cure the mind-rot of earlier exposure to procedural programming. – murray Jan 19 '13 at 15:25
@Misery have you seen this?: – Mr.Wizard Jan 20 '13 at 0:46

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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