Last active
March 19, 2021 22:34
-
-
Save Vicfred/babd3886fd25cfb64c41b22d8e872d92 to your computer and use it in GitHub Desktop.
pi approximation using random points in a circle
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
// approximate pi using random points in a square | |
// compile using: g++ pi.cpp -o pi | |
// and then run using: ./pi | |
#include <iostream> | |
#include <iomanip> | |
#include <random> | |
#include <cmath> | |
#include <chrono> | |
using namespace std; | |
int main() { | |
const long int TOTAL = 1e6; | |
cout.precision(15); | |
random_device r; | |
default_random_engine gen(r()); | |
uniform_real_distribution<long double> dist(0.0, 1.0); | |
long double inside; | |
inside = 1.0L; | |
long double x, y; | |
chrono::time_point<chrono::steady_clock> start, end; | |
start = chrono::steady_clock::now(); | |
for(long int i = 0L; i < TOTAL; ++i) { | |
// randomly select a point inside the square | |
x = dist(gen); | |
y = dist(gen); | |
//check if it's inside the circle | |
if(sqrt(x*x + y*y) <= 1.0L) | |
++inside; | |
} | |
end = chrono::steady_clock::now(); | |
chrono::duration<double> elapsed_seconds = end - start; | |
double t = elapsed_seconds.count(); | |
// compare it with the area of the square | |
// and multiply by 4 since we only considered | |
// one fourth of the circle | |
long double pi = 4.0L*(inside/TOTAL); | |
cout << "calculated: " << pi << endl; | |
cout << "actual: " << acos(-1.0L) << endl; | |
cout << "difference: " << fabs(pi-acos(-1.0L)) << endl; | |
cout << "it took " << t << " seconds" << endl; | |
return 0; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment