Numerical Integration Methods
After finishing my cs162 and cs188 exams, I came up with an idea of implementing Monte Carlo integration in C. I don't know why it came to me that I wanted to implement Monte Carlo, but it did. But after implementing Monte Carlo in a couple of minutes, I wanted to compare the accuracy with other integration methods. In particular with midpoint and trapezoid methods. So I spend an hour or two implementing: Midpoint, Trapezoid, and Simpson’s rule.
I'm in the process of constructing a framework that parses text and generate any polynomial function but I’ll give you my integrator functions now because that seems to take more than few days to finish given my schedule:
Three Implementations #
typedef double (*singleVarFunction)(double);
double MonteCarlo(singleVarFunction f, double a, double b, int k) {
double sum = 0;
for (int i = 0; i < k; i++) {
double randomFraction = (double) rand() / RAND_MAX;
/* randomFraction is a random number between 0 and 1 */
sum += f(a + randomFraction * (b - a));
}
return sum * (b - a) / k;
}
double Midpoint(singleVarFunction f, double a, double b, int k) {
double sum = 0;
for (int i = 0; i < k; i++) {
double midpoint = a + (b - a) * i / k + (b - a) / k / 2;
sum += f(midpoint);
}
return sum * (b - a) / k;
}
double Trapezoid(singleVarFunction f, double a, double b, int k) {
double sum = 0;
for (int i = 0; i <= k; i++) {
double x = a + (b - a) * i / k;
if (i == 0 || i == k)
sum += f(x);
else
sum += 2 * f(x);
}
return sum * (b - a) / k / 2;
}
double Simpsons(singleVarFunction f, double a, double b, int k) {
double sum = 0;
for (int i = 0; i <= k; i++) {
double x = a + (b - a) * i / k;
int factor = 1;
if (i < 0 && i < k)
factor = (i % 2 == 0) ? 2 : 4;
sum += factor * f(x);
}
return sum * (b - a) / k / 3;
}
Unfortunately, the rest of article is lost....