Advertisement
eitherlast

Integration

Dec 13th, 2017
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.43 KB | None | 0 0
  1. #include "stdafx.h"
  2. #include <stdio.h>
  3. #include <math.h>
  4.  
  5. double func(double x) {
  6.     return x * x;
  7. }
  8.  
  9. double IntegrateRect(double a, double b, double step) {
  10.     double ans = 0.0;
  11.     int stepRect = 0;
  12.     for (double x = a; x < b; x += step) {
  13.         ans += fmin(step, b - x) * func(x);
  14.         stepRect += 1;
  15.     }
  16.     return ans;
  17. }
  18.  
  19.  
  20.  
  21. double IntegrateTrap(double a, double b, double step) {
  22.     double ans = 0.0;
  23.     int stepTrap = 0;
  24.     for (double x = a; x < b; x += step) {
  25.         ans += fmin(step, b - x) * (func(x) + func(x + step)) / 2;
  26.         stepTrap += 1;
  27.     }
  28.     //printf("%d\n", stepTrap);
  29.     return ans;
  30. }
  31.  
  32. double IntegrateT(double a, double b, double precision) {
  33.     double area = (b - a) * (func(b) + func(a)) / 2;
  34.     double areaOld = -10000000.0;
  35.     int i = 1;
  36.     int step = 0;
  37.     while ((fabs(area - areaOld)) > precision) {
  38.         step += 1;
  39.         areaOld = area;
  40.         i++;
  41.         area = IntegrateTrap(a, b, (b - a) / i);
  42.     }
  43.     printf("%d\n", step);
  44.     return area;
  45.  
  46. }
  47.  
  48. int main(void) {
  49.     printf("Enter interval [a, b] and step (x)\n");
  50.  
  51.     double a, b, step;
  52.     scanf_s("%lf %lf %lf", &a, &b, &step);
  53.     printf("%f %f %f\n", a, b, step);
  54.     //a = 0.0; b = 1.0; step = 0.01;
  55.  
  56.     //printf("Integrated with rectangles:");
  57.     printf("Integrated with rectangles: %f\n", IntegrateRect(a, b, step));
  58.     printf("Integrated with trapezoids: %f\n", IntegrateTrap(a, b, step));
  59.     printf("Integrated with another function: %f\n", IntegrateT(a, b, step));
  60.  
  61.     scanf_s("%lf", &a);
  62.     return 0;
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement