Advertisement
dark-s0ul

lab4.cpp

Dec 26th, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.55 KB | None | 0 0
  1. using namespace std;
  2.  
  3. #include <vector>
  4. #include <cstdio>
  5. #include <cmath>
  6.  
  7. double f(double x) {
  8.     return 1.0 / x;
  9. }
  10.  
  11. double F(double x) {
  12.     return log(x);
  13. }
  14.  
  15. double Integral(double a, double b, int n) {
  16.     double sigma1 = 0, sigma2 = 0;
  17.  
  18.     double h = (b - a) / n;
  19.     for (int i = 1; i < n; i++) {
  20.         if (i % 2 == 0) sigma2 += f(a + i * h);
  21.         else sigma1 += f(a + i * h);
  22.     }
  23.     return h / 3 * (f(a) + f(b) + 4 * sigma1 + 2 * sigma2);
  24. }
  25.  
  26. int main() {
  27.     double errors[6], a = 1, b = 375, I = F(b) - F(a);
  28.  
  29.     int M = 29;
  30.  
  31.     printf("a = %g\nb = %g\n", a, b);
  32.     printf("I = F(b) - F(a) = %g\n", I);
  33.     printf("M = %d\n", a, b, I, M);
  34.  
  35.     printf("\nSimpson method\n");
  36.     printf("| given error | integration step |  integral value  | received error |\n");
  37.    
  38.     double q = 180 / ((b - a) * M);
  39.     int i = 0;
  40.     for (double eps = 1e-2; eps >= 1e-12; eps *= 1e-2) {
  41.         int n = 2 * ceil((b - a) / pow(eps * q, 0.25) / 2.0);
  42.  
  43.         double integral = Integral(a, b, n);
  44.         double error = fabs(I - integral);
  45.         errors[i++] = error;
  46.        
  47.         printf("| %.5e | %.10e | %14.14f | %.8e |\n", eps, (b - a) / n, integral, error);
  48.     }
  49.     printf("\nRunge method\n");
  50.     printf("| given error | integration step | received error |\n");
  51.    
  52.     for (int i = 0; i < 6; i++) {
  53.         double error = errors[i];
  54.  
  55.         int n = 2 * ceil((b - a) / pow(error, 0.25) / 2.0);
  56.         double h = (b - a) / n;
  57.        
  58.         double R = 0, In, I2n = Integral(a, b, n);
  59.         do {
  60.             In = I2n;
  61.             I2n = Integral(a, b, n *= 2);
  62.             R = fabs(In - I2n) / 15;
  63.         } while (R > error);
  64.        
  65.         printf("| %.5e | %.10e | %.8e |\n", error, h, R);
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement