segunda-feira, 22 de novembro de 2010

Como calcular o PI em C pelo Método de Monte Carlo

# include <stdio.h>
# include <stdlib.h>
# include <unistd.h>
# include <time.h>
# include <math.h>

int main(int argc, char *argv[])
{
                int N = 1000000;
                int n = 0;
                float x, y;
               
                srand( time( NULL ) );

                for(int i = 0; i < N; i++)
                {
                                x = (float) rand() / RAND_MAX;              
                                y = (float) rand() / RAND_MAX;

                               if(sqrt (x*x+y*y) <= 1)
                               {
                                               n++;
                               }
                }
                              
                float reasultado = (((float)4 * (float)n) / (float)N);
                printf("PI é igual a: %f", resultado);

                return 0;
}