Skip to content

Instantly share code, notes, and snippets.

@mzdun
Last active March 6, 2017 10:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mzdun/b1376203c57f54d2ceecebdb26327974 to your computer and use it in GitHub Desktop.
Save mzdun/b1376203c57f54d2ceecebdb26327974 to your computer and use it in GitHub Desktop.
#include <cmath>
#include <cstdio>
#include <random>
#include <range/v3/core.hpp>
#include <range/v3/algorithm/copy.hpp>
#include <range/v3/algorithm/count_if.hpp>
#include <range/v3/view/chunk.hpp>
#include <range/v3/view/iota.hpp>
#include <range/v3/view/take.hpp>
#include <range/v3/view/transform.hpp>
using namespace ranges;
// This code checks, how accurately we can calculate
// the value of ludolphine number by throwing darts at
// a square board with a cricle pinned in the middle of the
// board...
// inifinite view of dart pairs
template <typename Accuracy>
inline auto throw_darts_with(Accuracy& accuracy) {
using Sample = decltype(accuracy());
using Dart = std::pair<Sample, Sample>;
return view::iota(0) | view::transform([&](const auto) -> Dart {
return { accuracy(), accuracy() };
});
}
template <typename Accuracy>
inline auto throw_darts_with(Accuracy& accuracy, const long long radius) {
return view::transform([&](const auto how_many) {
const auto in_circle = count_if(
throw_darts_with(accuracy) | view::take(how_many),
[r_sqrd=radius*radius](const auto& dart) {
const auto x = std::get<0>(dart);
const auto y = std::get<1>(dart);
return r_sqrd >= (x * x + y * y);
});
const auto stats = 4.0 * in_circle / how_many;
return std::abs(stats - 3.14159265359);
});
};
inline auto power_of_10(const int max_exponent) {
return view::iota(0, max_exponent + 1)
| view::transform([](const auto pow) { return (long long)std::pow(10u, pow); });
}
int main()
{
std::mt19937 engine{ std::random_device{}() };
for (const auto radius : power_of_10(9)) {
std::uniform_int_distribution<long long> dist{ -radius, radius };
auto arm = [&]() { return dist(engine); };
for (const auto precision : power_of_10(7) | throw_darts_with(arm, radius))
std::printf("\t%12.9f", precision);
std::printf("\n");
}
}
@mzdun
Copy link
Author

mzdun commented Mar 6, 2017

R2 is a compilation issue fix, R3 uses count_if, removes board and chunk-of-2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment