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]}];
  • 2
    $\begingroup$ 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? $\endgroup$ – 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

| improve this answer | |
  • $\begingroup$ 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}] $\endgroup$ – cormullion Jan 19 '13 at 11:10
  • $\begingroup$ @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}] $\endgroup$ – Mr.Wizard Jan 19 '13 at 11:46
  • 4
    $\begingroup$ @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. $\endgroup$ – Niki Estner Jan 19 '13 at 14:29
  • 6
    $\begingroup$ @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. $\endgroup$ – murray Jan 19 '13 at 15:25
  • 2
    $\begingroup$ @Misery have you seen this?: mathematica.stackexchange.com/q/16869/121 $\endgroup$ – Mr.Wizard Jan 20 '13 at 0:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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