how to generate pi in c

perryh at pluto.rain.com perryh at pluto.rain.com
Sat Nov 6 08:12:00 UTC 2010


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;
>  20     
>  21     printf("%e\n", pi);
>  22     return(0);
>  23 }   
...
> This approximation is stupid ... Just take 'random' numbers and
> look whether they are in a circle (that's the a*a + b*b <= 1).

Not stupid, clever.  Very clever.  I rather doubt it resembles what
the OP had in mind, but it is a brilliant example of what can be
accomplished when one casts aside any perceived need to adopt a
conventional approach.

> The detail of this approximation heavily depends on the pseudo-rng
> you are using, as does its correctness

Perhaps it would be useful in a PRNG test suite?

> (e.g., when your 'rng' always returns 10, pi would be computed to
> be 10) ...

Bad example.  If abs(drand48()) always exceeded (0.5 * sqrt(2.0)),
a*a + b*b would always exceed 1.0, thus counter would never be
incremented and pi would be reported as zero.


More information about the freebsd-questions mailing list