1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <math.h> int main () { int in = 0; srand(time(NULL)); for(int i = 0; i < 1000000; i++) { float x = (rand()%1000000)/1000000.0; float y = (rand()%1000000)/1000000.0; double r = sqrt((pow(x,2)+pow(y,2))); if(r <= 1) in++; } printf("percent error=%fn", ((((4*in/1000000.0)-3.141592)/3.141592)*100)); printf("pi=%fn", (4*in/1000000.0)); return 0; } |
Tags: C++, cpp, monte carlo, pi

Thu, May 21, 2009
C++, Snippets