Created
January 20, 2021 16:00
-
-
Save insaneyilin/fae7382eacd10497f83871074805e8e9 to your computer and use it in GitHub Desktop.
C++ least square line fitting
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://www.varsitytutors.com/hotmath/hotmath_help/topics/line-of-best-fit.html | |
double CalcLineSlope(const std::vector<double>& x, | |
const std::vector<double>& y) { | |
const auto n = x.size(); | |
const auto s_x = std::accumulate(x.begin(), x.end(), 0.0); | |
const auto s_y = std::accumulate(y.begin(), y.end(), 0.0); | |
const auto s_xx = std::inner_product(x.begin(), x.end(), x.begin(), 0.0); | |
const auto s_xy = std::inner_product(x.begin(), x.end(), y.begin(), 0.0); | |
const auto slope = (n * s_xy - s_x * s_y) / (n * s_xx - s_x * s_x); | |
return slop; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment