Skip to content

Instantly share code, notes, and snippets.

@sjhalayka
Last active July 2, 2018 20:44
Show Gist options
  • Save sjhalayka/d89ebdc6e4b959748ccfd39d64939ba9 to your computer and use it in GitHub Desktop.
Save sjhalayka/d89ebdc6e4b959748ccfd39d64939ba9 to your computer and use it in GitHub Desktop.
// https://en.wikipedia.org/wiki/Simple_linear_regression
// https://en.wikipedia.org/wiki/Standard_deviation
float regression_line_slope(vector<float> &x, vector<float> &y)
{
if(x.size() != y.size())
return 0;
float x_mean = 0, y_mean = 0;
for(size_t i = 0; i < x.size(); i++)
{
x_mean += x[i];
y_mean += y[i];
}
x_mean /= static_cast<float>(x.size());
y_mean /= static_cast<float>(y.size());
float covariance = 0, variance = 0;
for(size_t i = 0; i < x.size(); i++)
{
float z = x[i] - x_mean;
covariance += z*(y[i] - y_mean);
variance += z*z;
}
return covariance / variance; // beta
}
float standard_deviation(const vector<float> &src)
{
float mean = 0;
float size = static_cast<float>(src.size());
for(size_t i = 0; i < src.size(); i++)
mean += src[i];
mean /= size;
float sq_diff = 0;
for(size_t i = 0; i < src.size(); i++)
{
float diff = src[i] - mean;
sq_diff += diff*diff;
}
sq_diff /= size;
return sqrt(sq_diff);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment