how to generate pi in c
perryh at pluto.rain.com
perryh at pluto.rain.com
Wed Nov 10 04:10:39 UTC 2010
Ian Smith <smithi at nimnet.asn.au> wrote:
> In freebsd-questions Digest, Vol 335, Issue 11, Message: 4
> On Sat, 06 Nov 2010 01:00:34 -0700 perryh at pluto.rain.com wrote:
> > Julian Fagir <gnrp at physik.tu-berlin.de> wrote:
> > > > Does anyone has a "generate-pi.c" source code?
> > ...
> > > 1 #include <stdlib.h>
> > > 2 #include <string.h>
> > > 3 #include <stdio.h>
> > > 4
> > > 5 // Change this for a more accurate result.
> > > 6 long max = 100000000;
> > > 7 double a, b;
> > > 8 double pi;
> > > 9 long counter;
> > > 10 long i;
> > > 11
> > > 12 int main() {
> > > 13 for (i = 0; i< max; i++) {
> > > 14 a = drand48();
> > > 15 b = drand48();
> > > 16 if (a*a + b*b <= 1)
> > > 17 counter++;
> > > 18 }
> > > 19 pi = 4*counter;
>
> Surely that should be 'pi = 4 * counter / max;' otherwise even if the
> integer counter were only 1 (of 100000000), pi would already be 4 :)
The part I snipped out included a note that it was only generating
the digits, not trying to show the decimal point placed properly.
With that understanding, and as long as max is a (large-ish) power
of 10, the division is not needed. (If the division were to be
inserted, at least one of its operands would need to be cast to
double, or pi would likely be reported as 3.0000 due to truncation.)
An approach more in keeping with the original would involve using
sprintf, and then inserting the decimal point into the resulting
string :)
More information about the freebsd-questions
mailing list