Advertisement
gashink_t

Aproximation(lab_12, VM)

Apr 13th, 2021
621
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <iostream>
  2. #include <iomanip>
  3. using namespace std;
  4.  
  5. void print(float* X, float* Y, int n);
  6.  
  7. int main()
  8. {
  9.     int n = 10;
  10.     float sum_x = 0, sum_y = 0, sum_x2 = 0, sum_y2 = 0, d,k, b;
  11.  
  12.     float* X = new float[n];
  13.     float* Y = new float[n];
  14.     X[0] = 1;
  15.     for (int i = 1; i < n; i++) X[i] = X[i - 1] + 0.1;
  16.     for (int i = 0; i < n; i++) Y[i] = pow(X[i], 2);
  17.     print(X, Y, n);
  18.  
  19.  
  20.     for (int i = 0; i < n; i++)
  21.     {
  22.         sum_x += X[i];          
  23.         sum_y += Y[i];          
  24.         sum_x2 += pow(X[i], 2);
  25.         sum_y2 += X[i] * Y[i];
  26.     }
  27.     d = sum_x2 * ((float)n) - pow(sum_x, 2);
  28.     k = (sum_y2 * ((float)n) - sum_x * sum_y) / d;
  29.     b = (sum_x2 * sum_y - sum_x * sum_y2) / d;  
  30.  
  31.     cout << "\ny(x) = " << k << " * x + " << b;
  32.  
  33.     cout << "\nComparison:\n";
  34.     for (int i = 0; i < n; i++)
  35.     {
  36.         cout << "Aprox y(x" << i << ") = " << k * X[i] + b << "\nTable y(x" << i << ") = " << Y[i] << "\nDifference = " << fabs(k * X[i] + b - Y[i]) << endl << endl;
  37.     }
  38. }
  39.  
  40.  
  41. void print(float* X, float* Y, int n)
  42. {
  43.     cout << "Table:\nX|";
  44.     for (int i = 0; i < n; i++)
  45.     {
  46.         cout << setw(10) << X[i];
  47.     }
  48.     cout << "\nY|";
  49.     for (int i = 0; i < n; i++)
  50.     {
  51.         cout << setw(10) << Y[i];
  52.     }
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement