Last active
March 6, 2017 09:06
-
-
Save arvabalazs/cfa0b80c26f0c95b57d5e7436674fd8f 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 <boost/range/algorithm/for_each.hpp> | |
#include <boost/range/algorithm/count_if.hpp> | |
#include <boost/range/irange.hpp> | |
#include <boost/range/adaptor/transformed.hpp> | |
#include <iostream> | |
#include <random> | |
#include <cmath> | |
using namespace boost; | |
using namespace adaptors; | |
constexpr auto pi=3.14159265359; | |
auto times(unsigned int n) | |
{ | |
return boost::irange(0u, n); | |
} | |
auto pi_approx(const double radius, const unsigned int point_count) | |
{ | |
static std::random_device rd; | |
static std::mt19937 rng{rd()}; | |
std::uniform_real_distribution<double> dist(0, radius); | |
auto inner_random_point_count=count_if(times(point_count), [&dist, &radius](auto) | |
{ | |
const auto x=dist(rng); | |
const auto y=dist(rng); | |
return std::sqrt(x*x+y*y)<=radius; | |
}); | |
return 4.0*inner_random_point_count/point_count; | |
} | |
int main() | |
{ | |
std::cout.setf(std::ios::fixed, std::ios::floatfield); | |
std::cout.precision(5); | |
for (auto radius: times(10) | transformed([](auto log10_radius){return std::pow(10, log10_radius);})) | |
{ | |
for (auto diff: times(8) | transformed([&radius](auto log10_point_count){return std::fabs(pi-pi_approx(radius, std::pow(10, log10_point_count)));})) | |
{ | |
std::cout<<diff<<" "; | |
} | |
std::cout<<std::endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment