Skip to content

Commit 54aac67

Browse files
committed
Update C++ Monte Carlo implementation.
1 parent f9fcc5f commit 54aac67

File tree

1 file changed

+5
-5
lines changed

1 file changed

+5
-5
lines changed

contents/monte_carlo_integration/code/c++/monte_carlo.cpp

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ inline bool in_circle(double x, double y, double r = 1) {
2222
*/
2323
double monte_carlo_pi(unsigned samples) {
2424
static std::default_random_engine generator;
25-
static std::uniform_real_distribution<double> dist(-1, 1);
25+
static std::uniform_real_distribution<double> dist(0, 1);
2626

2727
unsigned count = 0;
2828
for (unsigned i = 0; i < samples; ++i) {
@@ -33,7 +33,7 @@ double monte_carlo_pi(unsigned samples) {
3333
++count;
3434
}
3535

36-
return 4.0 * count / (double) samples;
36+
return 4.0 * count / samples;
3737
}
3838

3939
int main() {
@@ -42,7 +42,7 @@ int main() {
4242
std::cout << "Enter samples to use: ";
4343
std::cin >> samples;
4444

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);
45+
double pi_estimate = monte_carlo_pi(samples);
46+
std::cout << "Pi = " << pi_estimate << '\n';
47+
std::cout << "Percent error is: " << 100 * std::abs(pi_estimate - PI) / PI << " %\n";
4848
}

0 commit comments

Comments
 (0)