Advertisement
dark-s0ul

lab4 oksana

Dec 10th, 2017
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.00 KB | None | 0 0
  1. using namespace std;
  2. #include <vector>
  3. #include <cmath>
  4. #include <cstdio>
  5.  
  6. const double a = 1;
  7. const double b = 27;
  8.  
  9. double integral_function(double x) {
  10.     return pow(sin(x), 2);
  11. }
  12.  
  13. double atiderivative(double x) {
  14.     return -sin(2 * x) / 4 + x / 2;
  15. }
  16.  
  17. double second_derivative(double x) {
  18.     return 2 * (sin(2 * x) + x * cos(2 * x));
  19. }
  20.  
  21. double get_step(double eps) {
  22.     double max = 0;
  23.     double cur;
  24.     for (double i = a; i <= b; i += 0.01) {
  25.         cur = abs(second_derivative(i));
  26.         if (cur > max)
  27.             max = cur;
  28.     }
  29.  
  30.     double h = sqrt((12 * eps) / ((b - a) * max));
  31.     return h;
  32. }
  33.  
  34. double calculate_integral(double a, double b) {
  35.     return atiderivative(b) - atiderivative(a);
  36. }
  37.  
  38. double trapezoid(double a, double b, double h) {
  39.     double psum = integral_function(a) + integral_function(b);
  40.     int n = ceil((b - a) / h);
  41.     for (int i = 1; i < n; ++i)
  42.         psum = psum + 2.0 * integral_function(a + i * h);
  43.  
  44.     psum = (h / 2) * psum;
  45.  
  46.     return psum;
  47. }
  48.  
  49. void runge(double a, double b, double eps, double abs_error) {
  50.     double n = 1 / sqrt(eps);
  51.     double R;
  52.     double val_n, val_2n;
  53.     do {
  54.         val_n = trapezoid(a, b, (b - a) / n);
  55.         val_2n = trapezoid(a, b, (b - a) / (2 * n));
  56.         R = fabs(val_n - val_2n) / 3;
  57.         n *= 2;
  58.     } while (R > eps);
  59.  
  60.     double ex_value = calculate_integral(a, b);
  61.     printf("| %.12lf | %.5le | %.12lf |\n", abs_error, (b - a) / n, abs(val_2n - ex_value));
  62. }
  63.  
  64. int main() {
  65.     vector<double> errors;
  66.  
  67.     printf("Trapezoid method\n|  Eps  |     Step    | Exact value |  Error   |\n");
  68.     for (double eps = 0.1; eps > 1E-10; eps *= 0.01) {
  69.         double h = get_step(eps);
  70.         double value = trapezoid(a, b, h);
  71.         double integral = calculate_integral(a, b);
  72.         double error = fabs(value - integral);
  73.         printf("| %.0le | %.5le | %.9lf | %lf |\n", eps, h, integral, error);
  74.         errors.push_back(error);
  75.     }
  76.  
  77.     printf("\nRunge principle\n| Expected error |     Step    | Prodused error |\n");
  78.     double eps = 0.1;
  79.     for (int i = 0; i < errors.size(); ++i) {
  80.         runge(a, b, eps, errors[i]);
  81.         eps *= 0.01;
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement