# LinePlot in For loop

I have the following Mathematica code to approximate Pi as inspired by the Matlab code in George Zhao Ideas

    n = 100000;
count = 0;
For[i = 0, i <= n, i++;
roll = RandomVariate[UniformDistribution[{0, 1}]];
count = count + 4 Sqrt[1 - roll^2];]
{count, n, count/n}


I tried to insert ListPlot in the For loop but failed. My intention is to show how the {count/n} move per iteration. So, the ListPlot will get longer (approaching the Pi value) as the interation moves on.

Appreciate any help.

thanks.

-
For has no output, have a look at Table. – b.gatessucks Mar 24 '13 at 12:17
possible duplicate of Creating a table/Matrix during a For loop – Sjoerd C. de Vries Mar 28 '13 at 6:12

n = 100;
count = 0;
pies = {count};
Dynamic[ListPlot[pies, Joined -> True, PlotRange -> All]]


Pies will hold results as they are calculated. A dynamic ListPlot is drawn, it will be redrawn as For will be updating pies.

For[i = 1, i <= n, i++,
roll = RandomVariate[UniformDistribution[{0, 1}]];
count = count + 4 Sqrt[1 - roll^2];
AppendTo[pies, count/i]; Pause[.05]]


Pause will pause each redraw for 5/100 second. Note that For loop has four parts separated by comma. Your last two parts, increment and body are not separated but joined in compound expression by a semicolon.

-
Thanks, this is exactly what I intended. – mofai Mar 24 '13 at 13:28
@mofai Cool. Some of the programming here is not very exemplary. Yet everything always has pedagogical value. :) – BoLe Mar 24 '13 at 13:39

You could use Accumulate to build a list of the successive totals:

n = 1000000;
rolls = RandomVariate[UniformDistribution[{0, 1}], {n}];
data = Accumulate[4 Sqrt[1 - rolls^2]] / Range[n];

ListLinePlot[data[[;; ;; 1000]], GridLines -> {None, {Pi}},
PlotRange -> {3.13, 3.15}, DataRange -> {0, n}]


-
I tried your code but only the Axes and the Pi line are plotted. No data is plotted. – mofai Mar 24 '13 at 12:42
I see the line only if I change to DataRange -> {0, n} – cormullion Mar 24 '13 at 13:24
Thanks, not sure why I only got the same chart as above after editing the last code to ListLinePlot[data, GridLines -> {None, {Pi}}] – mofai Mar 24 '13 at 13:29
Thanks @cormullion, got that also. – mofai Mar 24 '13 at 13:31
Thanks @cormullion, maybe it's a version thing. The shorthand works for me in 8.0.4 – Simon Woods Mar 24 '13 at 13:31

It's more efficient to generate all random number in one go; one way is :

pi[n_] := Module[{roll = RandomVariate[UniformDistribution[{0, 1}], {n}]},
Total[4 Sqrt[1 - roll^2] ]/n]

ListPlot[{#, pi[#]} & /@ Range[10000]]

-
thanks. This is very helpful for me – mofai Mar 24 '13 at 12:45