Created
March 7, 2017 16:40
-
-
Save Oroles/ee51f79e699ebca89a4731ae052b8890 to your computer and use it in GitHub Desktop.
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 <random> | |
#include <vector> | |
#include <algorithm> | |
#include <iomanip> | |
#include <cmath> | |
#include <cassert> | |
template <typename T> | |
struct Point { | |
Point(T x, T y) | |
: m_x(x), | |
m_y(y) | |
{ | |
} | |
T m_x; | |
T m_y; | |
}; | |
template <typename T> | |
class Generator { | |
public: | |
Generator(int radius) | |
: gen(rd()), | |
dis(-radius,radius) | |
{} | |
public: | |
T generate() { | |
return dis(gen); | |
} | |
private: | |
std::random_device rd; | |
std::mt19937 gen; | |
std::uniform_real_distribution<> dis; | |
}; | |
template <typename T> | |
std::vector<T> generate_points(int count, int radius) { | |
std::vector<T> points; | |
points.reserve(count); | |
Generator<double> generator{radius}; | |
for (int i = 0; i < count; ++i) { | |
points.push_back({generator.generate(), generator.generate()}); | |
} | |
return points; | |
} | |
template <typename IT> | |
int count_inside(int radius, IT begin, IT end) { | |
return std::count_if(begin, end, [&radius](const typename IT::value_type p) { | |
return sqrt(p.m_x * p.m_x + p.m_y * p.m_y) < radius; }); | |
} | |
void generate_pi(int radius, int nr_points) { | |
std::vector<Point<double>> points = generate_points<Point<double>>(nr_points,radius); | |
std::cout << std::setprecision(10) << std::abs((4.0 * count_inside(radius, points.begin(), points.end()) / nr_points) - 3.14159265359); | |
} | |
template <typename T, typename Func> | |
constexpr std::vector<T> generate_values(const int min, const int max, Func f) { | |
std::vector<T> result; | |
result.reserve(max - min); | |
for (int i = min; i <= max; ++i) { | |
result.push_back(f(i)); | |
} | |
return result; | |
} | |
int main(int argc, char* argv[]) | |
{ | |
std::vector<int> radius_values = generate_values<int>(0, 9, [](int i){ return std::pow(10, i); }); | |
std::vector<int> points_values = generate_values<int>(0, 7, [](int i){ return std::pow(10, i); }); | |
for (auto radius : radius_values) { | |
for (auto nr_points : points_values) { | |
generate_pi(radius, nr_points); | |
std::cout << " "; | |
} | |
std::cout << std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment