Skip to content

Commit 33e1f17

Browse files
committed
Implement C++ version of Monte Carlo integration.
1 parent 8c5139c commit 33e1f17

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
#include <iostream>
2+
#include <cstdlib>
3+
#include <random>
4+
5+
constexpr double PI = 3.14159265358979323846264338;
6+
7+
/**
8+
* Check if the point (x, y) is within a circle of a given radius.
9+
* @param x coordinate one
10+
* @param y coordinate two
11+
* @param r radius of the circle (optional)
12+
* @return true if (x, y) is within the circle.
13+
*/
14+
inline bool in_circle(double x, double y, double r = 1) {
15+
return x * x + y * y < r * r;
16+
}
17+
18+
/**
19+
* Return an estimate of PI using Monte Carlo integration.
20+
* @param samples number of iterations to use
21+
* @return estimate of pi
22+
*/
23+
double monte_carlo_pi(unsigned samples) {
24+
static std::default_random_engine generator;
25+
static std::uniform_real_distribution<double> dist(-1, 1);
26+
27+
unsigned count = 0;
28+
for (unsigned i = 0; i < samples; ++i) {
29+
double x = dist(generator);
30+
double y = dist(generator);
31+
32+
if (x*x + y*y < 1)
33+
++count;
34+
}
35+
36+
return 4.0 * count / (double) samples;
37+
}
38+
39+
int main() {
40+
unsigned samples;
41+
42+
std::cout << "Enter samples to use: ";
43+
std::cin >> samples;
44+
45+
double pi = monte_carlo_pi(samples);
46+
printf("Pi = %f\n", pi);
47+
printf("Percent error is: %g %%\n", 100 * std::abs(pi - PI) / PI);
48+
}

contents/monte_carlo_integration/monte_carlo_integration.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,8 @@ each point is tested to see whether it's in the circle or not:
4343
[import:3-10, lang:"clojure"](code/clojure/monte_carlo.clj)
4444
{% sample lang="c" %}
4545
[import:7-9, lang:"c_cpp"](code/c/monte_carlo.c)
46+
{% sample lang="cpp" %}
47+
[import:7-16, lang:"c_cpp"](code/c++/monte_carlo.cpp)
4648
{% sample lang="js" %}
4749
[import:2-6, lang:"javascript"](code/javascript/monte_carlo.js)
4850
{% sample lang="hs" %}
@@ -100,6 +102,8 @@ Feel free to submit your version via pull request, and thanks for reading!
100102
[import, lang:"clojure"](code/clojure/monte_carlo.clj)
101103
{% sample lang="c" %}
102104
[import, lang:"c_cpp"](code/c/monte_carlo.c)
105+
{% sample lang="cpp" %}
106+
[import, lang:"c_cpp"](code/c++/monte_carlo.cpp)
103107
{% sample lang="js" %}
104108
[import, lang:"javascript"](code/javascript/monte_carlo.js)
105109
{% sample lang="hs" %}

0 commit comments

Comments
 (0)