Advertisement
MeShootIn

Linear regression

Apr 18th, 2019
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.86 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. #include <utility>
  4.  
  5. using namespace std;
  6.  
  7. pair <double, double> Get_y(vector <double> & x, vector <double> & y){
  8.     int N = x.size();
  9.    
  10.     double S_x, S_y, S_xy, S_x2;
  11.    
  12.     for(int i = 0; i < N; ++i){
  13.         S_x += x[i];
  14.         S_y += y[i];
  15.         S_xy += x[i] * y[i];
  16.         S_x2 += x[i] * x[i];
  17.     }
  18.    
  19.     double a = (N * S_xy - S_x * S_y) / (N * S_x2 - S_x * S_x);
  20.     double b = (S_x2 * S_y - S_x * S_xy) / (N * S_x2 - S_x * S_x);
  21.    
  22.     return make_pair(a, b);
  23. }
  24.  
  25. int main(){
  26.     cout << "Enter the number of points:\n";
  27.     int N;
  28.     cin >> N;
  29.    
  30.     vector <double> x(N);
  31.     vector <double> y(N);
  32.    
  33.     cout << "Enter " << N << " pairs of coordinates (x, y):\n";
  34.     for(int i = 0; i < N; ++i){
  35.         cin >> x[i] >> y[i];
  36.     }
  37.    
  38.     pair <double, double> line = Get_y(x, y);
  39.     cout << "a = " << line.first << ", b = " << line.second;
  40.    
  41.     system("PAUSE");
  42.     return 0;
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement