Hi,

> Does anyone has a "generate-pi.c" source code?
The solution of Ivan Klymenko is surely much more suffisticated, but as I
wrote this down, I just want to publish it... ;-)

  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 }   

Note that the result must be shifted to the potence of the max-int. I didn't
care for the problems with long-lengths now, but just dividing would not have
done the job.
Also, this implementations is stupid, as you see, no caring for the lengths
of the variables in the computer, if you go too far with your max, you will
surely become problems with the maximum number that can be represented.

The detail of this approximation heavily depends on the pseudo-rng you are
using, as does its correctness (e.g., when your 'rng' always returns 10, pi
would be computed to be 10). But if you have a good prng, it can approximate
pi to a fair amount of numbers.

If you had *real* random numbers (whatever that might be), you could even be
more approriate.

This approximation is stupid, but I like the simplicity of it (we did it in
uni last year). Just take 'random' numbers and look whether they are in a
circle (that's the a*a + b*b <= 1).


Regards, Julian

Attachment: signature.asc
Description: PGP signature

Reply via email to