added simple linear regression

This commit is contained in:
Ahmet Inan 2018-08-08 10:16:28 +02:00
commit beecb3bd2c
2 changed files with 56 additions and 0 deletions

View file

@ -54,3 +54,7 @@ for (uint8_t c: std::string("Hello World!")) crc(c);
assert(!crc(uint32_t(~0x1C291CA3)));
```
### [regression.hh](regression.hh)
Implemented [Simple linear regression](https://en.wikipedia.org/wiki/Simple_linear_regression) for [Regression analysis](https://en.wikipedia.org/wiki/Regression_analysis) of data.

52
regression.hh Normal file
View file

@ -0,0 +1,52 @@
/*
Regression analysis
Copyright 2018 Ahmet Inan <inan@aicodix.de>
*/
#ifndef REGRESSION_HH
#define REGRESSION_HH
namespace DSP {
template <typename TYPE>
class SimpleLinearRegression
{
TYPE avgX, avgY;
TYPE varX, covXY;
public:
SimpleLinearRegression(TYPE *x, TYPE *y, int LEN) : avgX(0), avgY(0), varX(0), covXY(0)
{
for (int i = 0; i < LEN; ++i) {
avgX += x[i];
avgY += y[i];
}
avgX /= LEN;
avgY /= LEN;
for (int i = 0; i < LEN; ++i) {
varX += (x[i] - avgX) * (x[i] - avgX);
covXY += (x[i] - avgX) * (y[i] - avgY);
}
}
TYPE xint()
{
return avgX - avgY * varX / covXY;
}
TYPE slope()
{
return covXY / varX;
}
TYPE yint()
{
return avgY - slope() * avgX;
}
TYPE operator () (TYPE x)
{
return yint() + slope() * x;
}
};
}
#endif