Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <cstdio>
- #include <cstdlib>
- typedef double(*function)(double);
- double integral(function f, double a, double b, unsigned step_count) {
- double sum = .0, step;
- size_t i;
- if (0 == step_count) return sum;
- step = (b - a) / (1.0 * step_count);
- for (i = 1; i < step_count; ++i) {
- sum += f(a + i * step);
- }
- sum += (f(a) + f(b)) / 2;
- sum *= step;
- return sum;
- }
- double f(double x) {
- return 2 + pow(x, 3);
- }
- double simpsonIntegral(double a, double b, int n, function f) {
- const double width = (b - a) / n;
- double simpson_integral = 0;
- for (int step = 0; step < n; step++) {
- const double x1 = a + step * width;
- const double x2 = a + (step + 1) * width;
- simpson_integral += (x2 - x1) / 6.0 * (f(x1) + 4.0 * f(0.5 * (x1 + x2)) + f(x2));
- }
- return simpson_integral;
- }
- int main() {
- printf("\ResultTRAP = %f\n", integral(f, 8, 14, 200));
- printf("\ResultPARA = %f\n", simpsonIntegral(8, 14, 200, f));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement