Skip to content

Instantly share code, notes, and snippets.

@lopesivan
Created June 26, 2017 04:23
Show Gist options
  • Save lopesivan/359d545547b094ebede6369ca998386f to your computer and use it in GitHub Desktop.
Save lopesivan/359d545547b094ebede6369ca998386f to your computer and use it in GitHub Desktop.
Solution to 'Pi Day Challenge' posted on Jonathan Boccara's blog. http://www.fluentcpp.com/2017/03/02/the-pi-day-challenge-for-expressive-code-in-c/
#include <iostream>
#include <iomanip>
#include <random>
int main(int argc, char* argv[])
{
const double REAL_PI = 3.14159265359;
std::random_device device;
std::mt19937 gen(device());
for (int n = 0; n < 10; n++)
{
for (int m = 0; m < 8; m++)
{
int number_of_points = pow(10.0, (double) m);
int radius = pow(10.0, (double) n);
std::uniform_real_distribution<double> dis(-radius, radius);
int counter = 0;
int i = 0;
while (i < number_of_points)
{
double x = dis(gen);
double y = dis(gen);
if (hypot(x, y) <= radius) counter++;
i++;
}
double pi = 4.0 * counter / (double) number_of_points;
double error = REAL_PI - pi;
std::cout << std::setprecision(9) << std::abs(error) << '\t';
}
std::cout << std::endl;
}
std::getchar();
return EXIT_SUCCESS;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment