Created
March 28, 2015 05:53
-
-
Save calebreister/634fe925c84fadd01c6f to your computer and use it in GitHub Desktop.
Simple numerical integration algorithm.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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