Advertisement
neongm

Untitled

Mar 4th, 2021
1,200
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.26 KB | None | 0 0
  1. #pragma once
  2. #include <iostream>
  3. #include <stdio.h>
  4. #include <vector>
  5. #include <numeric> // for std::accumulate()
  6. #include <cmath>   // for pow()
  7.  
  8. double coefficent_of_correlation(const std::vector<size_t>& values_x, const std::vector<size_t>& values_y)
  9. {
  10.     size_t mid_x = std::accumulate(values_x.begin(), values_x.end(), 0) / values_x.size();
  11.     size_t mid_y = std::accumulate(values_y.begin(), values_y.end(), 0) / values_y.size();
  12.    
  13.     std::vector<long long int> xi_minus_mid_x;
  14.     for (auto el : values_x) xi_minus_mid_x.push_back(el - mid_x);
  15.  
  16.     std::vector<long long int> xi_minus_mid_y;
  17.     for (auto el : values_y) xi_minus_mid_y.push_back(el - mid_y);  
  18.  
  19.     int long long upper_part = 0;
  20.     for (size_t i = 0; i < xi_minus_mid_x.size(); i++) upper_part += xi_minus_mid_x.at(i) * xi_minus_mid_y.at(i);
  21.  
  22.     unsigned long long x_sum = 0;
  23.     for (auto el : xi_minus_mid_x) x_sum += pow(el, 2);
  24.  
  25.     unsigned long long y_sum = 0;
  26.     for (auto el : xi_minus_mid_y) y_sum += pow(el, 2);
  27.  
  28.     int long long lower_part = pow(x_sum * y_sum, 0.5);
  29.  
  30.     return (double)upper_part / lower_part;
  31. }
  32.  
  33.    
  34. int main()
  35. {  
  36.     std::vector<size_t> x = {1, 2, 3, 4};
  37.     std::vector<size_t> y = {3, 4, 1, 2};
  38.    
  39.     std::cout << coefficent_of_correlation(x, y);
  40.     return 0;
  41. }
  42.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement