template<class TYPE>
BOOL LinearRegression(TYPE x[], TYPE y[], int n, TYPE &a, TYPE &b)
{
TYPE xs, ys, xys, xxs;
int i;
xs = 0;
ys = 0;
xys = 0;
xxs = 0;
for(i=0; i<n; i++)
{
xs += x[i];
ys += y[i];
xys += x[i]*y[i];
xxs += x[i]*x[i];
}
a = (xs*ys/n-xys)/(xs*xs/n-xxs);
b = (ys-a*xs)/n;
return TRUE;
};
template<class TYPE>
BOOL LinearReg2BC(TYPE x[][2], TYPE y[], int n, TYPE &b, TYPE &c)
{
TYPE tx[64], ty[64], x0;
int i;
for(i=0; i<n; i++)
{
x0 = x[i][0];
tx[i] = x[i][1] / x0;
ty[i] = y[i] / x0;
}
NMath::LinearRegression(tx, ty, n, c, b);
return TRUE;
}
template<class TYPE>
BOOL Equation2XSub(TYPE x[][2], TYPE y[], TYPE tx[][2], TYPE ty[], int i, int k)
{
tx[i][0] = x[i][0] - x[k][0];
tx[i][1] = x[i][1] - x[k][1];
ty[i] = y[i] - y[k];
return TRUE;
}
template<class TYPE>
BOOL LinearReg2X(TYPE x[][2], TYPE y[], int n, TYPE &a, TYPE &b, TYPE &c, TYPE *pq = NULL)
{
TYPE tx[64][2], ty[64];
int i;
TYPE x0s, x1s, ys, ry, ey, er, q;
if(n < 3)
return FALSE;
x0s = 0;
x1s = 0;
ys = 0;
for(i=0; i<n; i++)
{
x0s += x[i][0];
x1s += x[i][1];
ys += y[i];
}
for(i=1; i<n; i++)
Equation2XSub(x, y, tx, ty, i-1, i);
Equation2XSub(x, y, tx, ty, n-1, 0);
LinearReg2BC(tx, ty, n, b, c);
a = (ys - x0s*b - x1s*c)/n;
if(pq)
{
ey = 0;
er = 0;
for(i=0; i<n; i++)
{
ey += y[i]*y[i];
ry = a + b*x[i][0] + c*x[i][1];
er += (ry - y[i])*(ry - y[i]);
}
q = (ey-er)/ey;
*pq = q;
return TRUE;
}
return TRUE;
}
标签:二元,tx,ty,int,回归,64,线性,ys,TYPE
From: https://www.cnblogs.com/zzz3265/p/17997858