Skip to content

Instantly share code, notes, and snippets.

@calebreister
Created March 28, 2015 05:53
Show Gist options
  • Save calebreister/634fe925c84fadd01c6f to your computer and use it in GitHub Desktop.
Save calebreister/634fe925c84fadd01c6f to your computer and use it in GitHub Desktop.
Simple numerical integration algorithm.
// https://helloacm.com/c-function-to-compute-numerical-integral-using-function-pointers/
double integral(double(*f)(double x), double a, double b, int n) {
double step = (b - a) / n; // width of each small rectangle
double area = 0.0; // signed area
for (int i = 0; i < n; i ++) {
area += f(a + (i + 0.5) * step) * step; // sum up each small rectangle
}
return area;
}
int main()
{
cout.precision(7);
cout << integral(cos, 0, M_PI / 2, 10);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment