Skip to content

Small change to monte_carlo.c #501

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 17, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 12 additions & 13 deletions contents/monte_carlo_integration/code/c/monte_carlo.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,19 +4,18 @@
#include <stdlib.h>
#include <time.h>

bool in_circle(double x, double y, double radius) {
return x * x + y * y < radius * radius;
bool in_circle(double x, double y) {
return x * x + y * y < 1;
}

double monte_carlo(int samples) {
double radius = 1.0;
int count = 0;
double monte_carlo(unsigned int samples) {
unsigned int count = 0;

for (int i = 0; i < samples; ++i) {
double x = (double)rand() * radius / RAND_MAX;
double y = (double)rand() * radius / RAND_MAX;
for (unsigned int i = 0; i < samples; ++i) {
double x = (double)rand() / RAND_MAX;
double y = (double)rand() / RAND_MAX;

if (in_circle(x, y, radius)) {
if (in_circle(x, y)) {
count += 1;
}
}
Expand All @@ -28,9 +27,9 @@ int main() {
srand(time(NULL));

double estimate = monte_carlo(1000000);
printf("The estimate of pi is %f\n", estimate);
printf("Percentage error: %0.2f%\n", 100 * fabs(M_PI - estimate) / M_PI);

printf("The estimate of pi is %g\n", estimate);
printf("Percentage error: %0.2f%%\n", 100 * fabs(M_PI - estimate) / M_PI);

return 0;
}