-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmontecarlo_pi.cpp
More file actions
53 lines (42 loc) · 1.52 KB
/
montecarlo_pi.cpp
File metadata and controls
53 lines (42 loc) · 1.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <fstream>
#include <random>
#include <cmath>
#include <cstdlib>
int main() {
const int total_points = 1000000;
int inside_circle = 0;
std::ofstream outfile("pi_approximation_data.csv");
outfile << "Step,ApproxPi\n";
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dis(0.0, 1.0);
for (int i = 1; i <= total_points; ++i) {
double x = dis(gen);
double y = dis(gen);
if (x * x + y * y <= 1.0) {
++inside_circle;
}
if (i % 1000 == 0) {
double pi_estimate = 4.0 * inside_circle / i;
outfile << i << "," << pi_estimate << "\n";
}
}
double final_pi = 4.0 * inside_circle / total_points;
std::cout << "Final Approximation of Pi = " << final_pi << std::endl;
outfile.close();
// gnuplot script
std::ofstream gnuplot_script("plot_pi.gp");
gnuplot_script << "set datafile separator ','\n";
gnuplot_script << "set title 'Monte Carlo Approximation of Pi'\n";
gnuplot_script << "set xlabel 'Number of Points'\n";
gnuplot_script << "set ylabel 'Estimated Pi'\n";
gnuplot_script << "set grid\n";
gnuplot_script << "set key left top\n";
gnuplot_script << "plot 'pi_approximation_data.csv' using 1:2 with lines title 'Approximated Pi', \\\n";
gnuplot_script << " 3.141592653589793 with lines linestyle 2 title 'Actual Pi'\n";
gnuplot_script.close();
// Run gnuplot
system("gnuplot -p plot_pi.gp");
return 0;
}