-
-
Save mzdun/b1376203c57f54d2ceecebdb26327974 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 <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"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
R2 is a compilation issue fix, R3 uses count_if, removes board and chunk-of-2