Advertisement
dark-s0ul

Untitled

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