Skip to content

Instantly share code, notes, and snippets.

@gangsterveggies
Created September 10, 2013 15:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gangsterveggies/6511133 to your computer and use it in GitHub Desktop.
Save gangsterveggies/6511133 to your computer and use it in GitHub Desktop.
A Monte Carlo Integral calculator
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
double f(double x)
{
return exp(x) * x;
}
double random(int fs, int ls)
{
return ((rand() / (double) RAND_MAX) * (ls - fs)) + fs;
}
int main()
{
srand(time(NULL));
int N, it, b, a, i, j;
// For a = 2 and b = 5 and f(x) = x * e^x
double realvalue = 586.264;
printf("Input number of iterations: ");
scanf("%d", &it);
printf("Input number of samples: ");
scanf("%d", &N);
printf("Input the boundaries (a, b): ");
scanf("%d %d", &a, &b);
double sum = 0, ans = 0;
// Monte Carlo Method Calculation
for (i = 0; i < it; i++)
for (j = 0; j < N; j++)
{
double vl = random(a, b);
sum += f(vl);
}
sum /= it;
sum = (sum * (b - a)) / N;
// Midpoint Rule Calculation
double dif = (b - a) / ((double)N);
for (j = 0; j < N; j++)
{
double vl = j * dif + a;
ans += f(vl) * dif;
}
printf("Real Value: %lf\n", realvalue);
printf("Integral: %lf, error: %0.3lf%%\n", sum, (100 * fabs(sum - realvalue) / realvalue));
printf("Integral (using the midpoint rule): %0.3lf, error %0.3lf%%\n", ans, (100 * fabs(ans - realvalue) / realvalue));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment