diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index 6b3d1ec61..f188deacc 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -54,4 +54,6 @@ Arun Sahadeo
NIFR91
-Michal Hanajik \ No newline at end of file +Michal Hanajik +
+Bendik Samseth diff --git a/contents/monte_carlo_integration/code/c++/monte_carlo.cpp b/contents/monte_carlo_integration/code/c++/monte_carlo.cpp new file mode 100644 index 000000000..beff97170 --- /dev/null +++ b/contents/monte_carlo_integration/code/c++/monte_carlo.cpp @@ -0,0 +1,48 @@ +#include +#include +#include + +constexpr double PI = 3.14159265358979323846264338; + +/** + * Check if the point (x, y) is within a circle of a given radius. + * @param x coordinate one + * @param y coordinate two + * @param r radius of the circle (optional) + * @return true if (x, y) is within the circle. + */ +inline bool in_circle(double x, double y, double r = 1) { + return x * x + y * y < r * r; +} + +/** + * Return an estimate of PI using Monte Carlo integration. + * @param samples number of iterations to use + * @return estimate of pi + */ +double monte_carlo_pi(unsigned samples) { + static std::default_random_engine generator; + static std::uniform_real_distribution dist(0, 1); + + unsigned count = 0; + for (unsigned i = 0; i < samples; ++i) { + double x = dist(generator); + double y = dist(generator); + + if (in_circle(x, y)) + ++count; + } + + return 4.0 * count / samples; +} + +int main() { + unsigned samples; + + std::cout << "Enter samples to use: "; + std::cin >> samples; + + double pi_estimate = monte_carlo_pi(samples); + std::cout << "Pi = " << pi_estimate << '\n'; + std::cout << "Percent error is: " << 100 * std::abs(pi_estimate - PI) / PI << " %\n"; +} diff --git a/contents/monte_carlo_integration/monte_carlo_integration.md b/contents/monte_carlo_integration/monte_carlo_integration.md index 8a8544e73..631462eff 100644 --- a/contents/monte_carlo_integration/monte_carlo_integration.md +++ b/contents/monte_carlo_integration/monte_carlo_integration.md @@ -43,6 +43,8 @@ each point is tested to see whether it's in the circle or not: [import:3-10, lang:"clojure"](code/clojure/monte_carlo.clj) {% sample lang="c" %} [import:7-9, lang:"c_cpp"](code/c/monte_carlo.c) +{% sample lang="cpp" %} +[import:7-16, lang:"c_cpp"](code/c++/monte_carlo.cpp) {% sample lang="js" %} [import:2-6, lang:"javascript"](code/javascript/monte_carlo.js) {% sample lang="hs" %} @@ -100,6 +102,8 @@ Feel free to submit your version via pull request, and thanks for reading! [import, lang:"clojure"](code/clojure/monte_carlo.clj) {% sample lang="c" %} [import, lang:"c_cpp"](code/c/monte_carlo.c) +{% sample lang="cpp" %} +[import, lang:"c_cpp"](code/c++/monte_carlo.cpp) {% sample lang="js" %} [import, lang:"javascript"](code/javascript/monte_carlo.js) {% sample lang="hs" %}