Advertisement
MadCortez

Untitled

Nov 18th, 2020
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.05 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <cstdio>
  4. #include <cstdlib>
  5.  
  6. typedef double(*function)(double);
  7.  
  8. double integral(function f, double a, double b, unsigned step_count) {
  9.     double sum = .0, step;
  10.     size_t i;
  11.     if (0 == step_count) return sum;
  12.  
  13.     step = (b - a) / (1.0 * step_count);
  14.     for (i = 1; i < step_count; ++i) {
  15.         sum += f(a + i * step);
  16.     }
  17.     sum += (f(a) + f(b)) / 2;
  18.     sum *= step;
  19.     return sum;
  20. }
  21.  
  22. double f(double x) {
  23.     return 2 + pow(x, 3);
  24. }
  25.  
  26. double simpsonIntegral(double a, double b, int n, function f) {
  27.     const double width = (b - a) / n;
  28.  
  29.     double simpson_integral = 0;
  30.     for (int step = 0; step < n; step++) {
  31.         const double x1 = a + step * width;
  32.         const double x2 = a + (step + 1) * width;
  33.  
  34.         simpson_integral += (x2 - x1) / 6.0 * (f(x1) + 4.0 * f(0.5 * (x1 + x2)) + f(x2));
  35.     }
  36.  
  37.     return simpson_integral;
  38. }
  39.  
  40. int main() {
  41.     printf("\ResultTRAP = %f\n", integral(f, 8, 14, 200));
  42.     printf("\ResultPARA = %f\n", simpsonIntegral(8, 14, 200, f));
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement