Skip to content

Instantly share code, notes, and snippets.

@gnitnaw
Created May 25, 2015 17:45
Show Gist options
  • Save gnitnaw/56c6686fcbeb0c9eb3ed to your computer and use it in GitHub Desktop.
Save gnitnaw/56c6686fcbeb0c9eb3ed to your computer and use it in GitHub Desktop.
Integral with Simpson's_rule
#include <stdio.h> // printf
#include <math.h> // sin, atan
double simpson(double a, double b, double (*func)(double)); // Simpson's_rule
double integral(double xi, double xf, int n, double (*func)(double)); // Integral with some tools
int main() {
double pi = 4.0*atan(1.0);
double surface;
for (int i=10; i<=50; i+=2) {
surface = integral(0.0, pi, i, sin);
printf("N = %d, Surface = %.22lf \n", i, surface);
}
return 0;
}
double simpson(double a, double b, double (*func)(double)){
double f = func(a) + 4*func((a+b)/2) + func(b);
f *= (b-a)/6;
return f;
}
double integral(double xi, double xf, int n, double (*func)(double)){
double xStep = (xf-xi)/n;
double surface = 0.0;
double x1, x2;
for (int i=0; i<n; ++i) {
x1 = xStep * i;
x2 = xStep * (i+1);
surface += simpson(x1, x2, func);
}
return surface;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment