Created
February 23, 2012 04:33
-
-
Save mimshwright/1890218 to your computer and use it in GitHub Desktop.
Solution to Monte Carlo problem for Coding Dojo Feb 2012 by Mims H. Wright (in C++)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stdlib.h> | |
#include <cmath> | |
#include <ctime> | |
using namespace std; | |
int main() | |
{ | |
int reps = 0; | |
cout << "Enter number of repititions then press enter." << endl; | |
cin >> reps; | |
cout << "Calculating π in " << reps << " steps" << endl; | |
// initialize random seed: | |
srand ( time(0) ); | |
int i = 0, inCircle = 0; | |
double x = 0, y = 0, d = 0.0; | |
while (i++ < reps) { | |
x = ((double) rand() / RAND_MAX); | |
y = ((double) rand() / RAND_MAX); | |
// Find the distance from the origin. If it's less than the radius of the circle, it's inside the circle. | |
d = sqrt( x*x + y*y ); | |
inCircle += d < 1 ? 1 : 0; | |
} | |
double pi = ((double)inCircle / reps) * 4.0; | |
cout << "Pi is roughly " << pi << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment