Advertisement
dark-s0ul

oksana lab4

Dec 12th, 2017
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.89 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.     for (double i = a; i <= b; i += 0.01) {
  24.         double cur = abs(second_derivative(i));
  25.         if (cur > max) max = cur;
  26.     }
  27.  
  28.     return sqrt((12 * eps) / ((b - a) * max));
  29. }
  30.  
  31. double calculate_integral(double a, double b) {
  32.     return atiderivative(b) - atiderivative(a);
  33. }
  34.  
  35. double trapezoid(double a, double b, double h) {
  36.     double psum = integral_function(a) + integral_function(b);
  37.     int n = (b - a) / h;
  38.     for (int i = 1; i < n; ++i) {
  39.         psum = psum + 2.0 * integral_function(a + i * h);
  40.     }
  41.     return (h / 2) * psum;
  42. }
  43.  
  44. void runge(double a, double b, double error) {
  45.     double n = 2 * ceil(1 / sqrt(error) * 0.5);
  46.     double val_2n = trapezoid(a, b, (b - a) / n), R;
  47.     do {
  48.         double val_n = val_2n;
  49.         val_2n = trapezoid(a, b, (b - a) / (n *= 2));
  50.         R = fabs(val_n - val_2n) / 3;
  51.     } while (R > error);
  52.     printf("| %.7e | %.5e | %.8e |\n", error, (b - a) / n, abs(val_2n - calculate_integral(a, b)));
  53. }
  54.  
  55. int main() {
  56.     vector<double> errors;
  57.  
  58.     printf("Trapezoid method\n|  Eps  |     Step    | integral value | Prodused error |\n");
  59.     for (double eps = 0.1; eps > 1E-10; eps *= 0.01) {
  60.         int n = 2 * ceil((b - a) / get_step(eps) * 0.5);
  61.         double h = (b - a) / n;
  62.  
  63.         double value = trapezoid(a, b, h);
  64.         double error = fabs(value - calculate_integral(a, b));
  65.         printf("| %.0e | %.5e | %.11f | %.8e |\n", eps, h, value, error);
  66.         errors.push_back(error);
  67.     }
  68.  
  69.     printf("\nRunge principle\n|  Given error  |     Step    | Prodused error |\n");
  70.     for (int i = 0; i < errors.size(); ++i) {
  71.         runge(a, b, errors[i]);
  72.     }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement