6
The Monte-Carlo algorithm
- #include <stdio.h>
- #include <stdlib.h>
- #include <time.h>
- int main( ) {
- const long NTHROWS = 1000000; // how many times do we throw the dart
- unsigned long inside = 0;
- unsigned seed = time( 0 );
- double x, y;
- unsigned long i;
- srand( seed );
- for ( i = 0; i < NTHROWS; i++ ) {
- x = (double)rand()/RAND_MAX;
- y = (double)rand()/RAND_MAX;
- if ( x*x + y*y < 1.0 )
- inside++;
- }
- printf("PI=%f\n", 4.0*inside/NTHROWS);
- }
$ gcc -o mc mc.c
$ ./mc
PI=3.139084
Change NTHROWS to 10000000 to obtain a closer value (and test the speed of your CPU):
$ gcc -o mc mc.c
$ ./mc
PI=3.141202
Comments