4

The Monte-Carlo algorithm

  1. #include <stdio.h>
  2.  
  3. #include <stdlib.h>
  4. #include <time.h>
  5.  
  6. int main( ) {
  7.     const long NTHROWS = 1000000;   // how many times do we throw the dart
  8.  
  9.     unsigned long inside = 0;
  10.     unsigned seed = time( 0 );
  11.  
  12.     double x, y;
  13.     unsigned long i;
  14.    
  15.     srand( seed );
  16.  
  17.     for ( i = 0; i < NTHROWS; i++ ) {
  18.         x = (double)rand()/RAND_MAX;
  19.         y = (double)rand()/RAND_MAX;
  20.         if ( x*x + y*y < 1.0 )
  21.             inside++;
  22.     }
  23.     printf("PI=%f\n", 4.0*inside/NTHROWS);
  24. }
$ 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

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].