Monte Carlo Generation of Pi

[code lang="cpp"]#include
#include
#include
#include
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;
}
[/code]

Related posts:

  1. Euler’s Constant Calculate Euler’s constant. [code lang="cpp"]#include /** * This code will calculate e * as the sum of the infinite series...

Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Notify me of followup comments via e-mail. You can also subscribe without commenting.