Class GA{
/// <summary>
/// 求自变量x与因变量y的回归方程系数
/// </summary>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="n">自变量个数</param>
/// <param name="m">自变量数据组数个数</param>
/// <param name="b">返回b1,b2,b3...bn即:回归系数</param>
/// <param name="b0">方程组中b0的值</param>
public string DYHGFC(float[,] x, float[] y, int n, int m, ref float[] b, ref float b0) {
//实现公式Y=B0+B1*X1+B2*X2+B3*X3+...+Bn*Xn
//设有n个自变量,m组数据
//L12=L21=自变量X11*自变量X21+自变量X12*自变量X22+自变量X13*自变量X23+...+自变量X1m*自变量X2m
//-(自变量X11+自变量X12+自变量X13+...+自变量X1m)*(自变量X21+自变量X22+自变量X23+...+自变量X2m)/x.length
//B0=Yavg-(B1*X1avg+B2*X2avg+B3*X3avg+...+Bn*Xnavg)
float[,] xx = new float[n + 1, n + 1];//建立一个离差矩阵
for (int i = 0; i <= n; i++) {
float v1 = 0;//设v1的结果为:自变量X11*自变量X21+自变量X12*自变量X22+自变量X13*自变量X23+...+自变量X1m*自变量X2m
float v2 = 0;//设v2的结果为:(自变量X11+自变量X12+自变量X13+...+自变量X1m)
float v3 = 0;//设v3的结果为:(自变量X21+自变量X22+自变量X23+...+自变量X2m)
for (int j = 0; j <= n; j++) {
for (int k = 0; k < m; k++) {
v1 += x[i, k] * x[j, k];
v2 += x[i, k];
v3 += x[j, k];
}
//Console.WriteLine(v1 - v2 * v3 / m);
xx[i, j] = v1 - v2 * v3 / m;
v1 = v2 = v3 = 0;
}
}
//解方程组,求各个变量x的系数
b = Gause(xx, n);
float[] xAvg = new float[n];
float yAvg = 0;
for (int i = 0; i < n; i++) {
float avg = 0;
for (int j = 0; j < m; j++) {
avg += x[i, j];
}
xAvg[i] = avg / m;
}
yAvg = y.Average();
float t = 0;//定义一个临时变量保存:B1*X1avg+B2*X2avg+B3*X3avg+...+Bn*Xnavg 的值
for (int i = 0; i < n; i++) {
t += b[i] * xAvg[i];
}
b0 = yAvg - (t);
string fc = b0.ToString("0.0000");
for (int i = 0; i < n; i++) {
string fh = " + ";
fh = Math.Round(b[i], 4) < 0 ? "" : " + ";
fc += fh + Math.Round(b[i], 4) + " * X" + (i + 1).ToString();
}
return fc;
}
/// <summary>
/// 高斯消元求解方程组的解
/// </summary>
/// <param name="a"></param>
/// <param name="n"></param>
/// <returns></returns>
static float[] Gause(float[,] a, int n) {
int i, j, k;
int rank, columm;
float temp, l, s;
float[] x = new float[n];
for (i = 0; i <= n - 2; i++) {
rank = i;
columm = i;
for (j = i + 1; j <= n - 1; j++) //选主元
if (a[j, i] > a[i, i]) {
rank = j;
columm = i;
}
for (k = 0; k <= n; k++) //主元行变换
{
temp = a[i, k];
a[i, k] = a[rank, k];
a[rank, k] = temp;
}
for (j = i + 1; j <= n - 1; j++) //解线性方程
{
l = a[j, i] / a[i, i];
for (k = i; k <= n; k++)
a[j, k] = a[j, k] - l * a[i, k];
}
}
x[n - 1] = a[n - 1, n] / a[n - 1, n - 1]; //回代方程求解x
for (i = n - 2; i >= 0; i--) {
s = 0;
for (j = i + 1; j <= n - 1; j++)
s = s + a[i, j] * x[j];
x[i] = (a[i, n] - s) / a[i, i];
}
return x;
}
}