Skip to content

Instantly share code, notes, and snippets.

@insaneyilin
Created January 20, 2021 16:00
Show Gist options
  • Save insaneyilin/fae7382eacd10497f83871074805e8e9 to your computer and use it in GitHub Desktop.
Save insaneyilin/fae7382eacd10497f83871074805e8e9 to your computer and use it in GitHub Desktop.
C++ least square line fitting
// 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