Advertisement
dark-s0ul

lab4

Jan 18th, 2018
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.52 KB | None | 0 0
  1. #include <vector>
  2. #include <cstdio>
  3. #include <cmath>
  4.  
  5. double f(double x) {
  6.     return (cos(x) - x * sin(x)) / pow(cos(x), 2);
  7. }
  8.  
  9. double F(double x) {
  10.     return -x / cos(x) - 2 * log(cos(x * 0.5) - sin(x * 0.5)) + 2 * log(sin(x * 0.5) + cos(x * 0.5));
  11. }
  12.  
  13. double myintegral(double a, double b, int n) {
  14.     double sigma1 = 0;
  15.     double sigma2 = 0;
  16.  
  17.     double h = (b - a) / (double) n;
  18.     for (int i = 1; i < n; i++) {
  19.         if (i % 2 == 0) sigma2 += f(a + i * h);
  20.         else sigma1 += f(a + i * h);
  21.     }
  22.     return h / 3.0 * (f(a) + f(b) + 4.0 * sigma1 + 2.0 * sigma2);
  23. }
  24.  
  25. int main() {
  26.     std::vector<double> errors;
  27.  
  28.     double a = -1.5;
  29.     double b = 1.5;
  30.     double I = F(b) - F(a);
  31.  
  32.     double q = 180.0 / ((b - a) * 20000000.0);
  33.  
  34.     printf("\nsimpson\n| given error |       step       |       value       | received error |\n");
  35.     for (double eps = 1e-2; eps >= 1e-12; eps *= 1e-2) {
  36.         int n = (int((b - a) / pow(eps * q, 0.25)) >> 1) << 1;
  37.  
  38.         double value = myintegral(a, b, n);
  39.         errors.push_back(fabs(I - value));
  40.  
  41.         printf("| %.5e | %.10e | %13.13f | %.8e |\n", eps, (b - a) / (double) n, value, errors.back());
  42.     }
  43.     printf("\nrunge\n| given error |       step       | received error |\n");
  44.  
  45.     for (const double &error : errors) {
  46.         int n = (int((b - a) / pow(error, 0.25)) >> 1) << 1;
  47.  
  48.         double R = 0;
  49.         double I2n = myintegral(a, b, n);
  50.         do {
  51.             double In = I2n;
  52.             I2n = myintegral(a, b, n <<= 1);
  53.             R = fabs(In - I2n) / 15.0;
  54.         } while (R > error);
  55.  
  56.         printf("| %.5e | %.10e | %.8e |\n", error, (b - a) / (double)n, R);
  57.     }
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement