C# 多点最小二乘法拟合平面算法
/// <summary> /// 实现三阶行列式求值计算 /// </summary> /// <param name="x1"></param> /// <param name="y1"></param> /// <param name="z1"></param> /// <param name="x2"></param> /// <param name="y2"></param> /// <param name="z2"></param> /// <param name="x3"></param> /// <param name="y3"></param> /// <param name="z3"></param> /// <returns></returns> private double gDeterm3(double x1, double y1, double z1, double x2, double y2, double z2, double x3, double y3, double z3) { return x1 * y2 * z3 + y1 * z2 * x3 + z1 * x2 * y3 - z1 * y2 * x3 - y1 * x2 * z3 - x1 * z2 * y3; } private void button1_Click(object sender, EventArgs e) { //初始化坐标值 double[] xArr = new double[16] { 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3 }; double[] yArr = new double[16] { 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3 }; double[] zArr = new double[16] { 5, 4, 1, 1, 9, 7, 3, -1, 9, 5, 2, -3, 1, -2, 0, 3 }; //初始化需要的变量 double x1 = 0d, x2 = 0d, y1 = 0d, y2 = 0d, z1 = 0d, xz = 0d, yz = 0d, xy = 0d, r = 0d;
//计算 for (int i = 0; i < xArr.Length; i++) { x1 += xArr[i]; x2 += xArr[i] * xArr[i]; xz += xArr[i] * zArr[i]; y1 += yArr[i]; y2 += yArr[i] * yArr[i]; yz += yArr[i] * zArr[i]; z1 += zArr[i]; xy += xArr[i] * yArr[i]; } string res = ""; r = gDeterm3(x2, xy, x1, xy, y2, y1, x1, y1, xArr.Length); res += "R ="+r+","; if (r != 0) { res += "A =" + gDeterm3(xz, xy, x1, yz, y2, y1, z1, y1, xArr.Length) / r + ","; res += "B =" + gDeterm3(x2, xz, x1, xy, yz, y1, x1, z1, xArr.Length) / r + ","; res += "C =" + gDeterm3(x2, xy, xz, xy, y2, yz, x1, y1, z1) / r; } this.label1.Text = res; }