Date: Fri, 5 Nov 2010 19:50:19 +0100 From: Julian Fagir <gnrp@physik.tu-berlin.de> To: freebsd-questions@freebsd.org Subject: Re: how to generate pi in c Message-ID: <20101105195019.4462c479@adolfputzen> In-Reply-To: <AANLkTikaBYi0d4dvLnc=vxuPDWQHDqrVJrz=iVkECeO=@mail.gmail.com> References: <AANLkTikaBYi0d4dvLnc=vxuPDWQHDqrVJrz=iVkECeO=@mail.gmail.com>
next in thread | previous in thread | raw e-mail | index | archive | help
--Sig_/QJ_Ts1XzibFJAAaulhvm4P1 Content-Type: text/plain; charset=US-ASCII Content-Transfer-Encoding: quoted-printable 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=20 5 // Change this for a more accurate result. 6 long max =3D 100000000; 7 double a, b; 8 double pi; 9 long counter; 10 long i; 11=20 12 int main() { 13 for (i =3D 0; i< max; i++) { 14 a =3D drand48(); 15 b =3D drand48(); 16 if (a*a + b*b <=3D 1) 17 counter++; 18 } =20 19 pi =3D 4*counter; 20 =20 21 printf("%e\n", pi); 22 return(0); 23 } =20 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 ha= ve 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 <=3D 1). Regards, Julian --Sig_/QJ_Ts1XzibFJAAaulhvm4P1 Content-Type: application/pgp-signature; name=signature.asc Content-Disposition: attachment; filename=signature.asc -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.9 (GNU/Linux) iEUEARECAAYFAkzUUewACgkQFV4nWcOPv/CtWACYwrAxjpbfDm0hbnskzxhN4SO+ IgCeI3KotjqE7fWPfZ32MKt0zES5Ero= =nlIO -----END PGP SIGNATURE----- --Sig_/QJ_Ts1XzibFJAAaulhvm4P1--
Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?20101105195019.4462c479>