C#,码海拾贝(27)——求解“对称方程组”的“分解法”之C#源代码,《C#数值计算算法编程》源代码升级改进版
// C#数值计算算法编程// 码海拾贝(27)——求解“对称方程组”的“分解法”之C#源代码using System;
class SymmetricEquationSolver{
static void Main()
{
// 定义对称方程组的系数矩阵 double[,] A = { {4,2,1 }, {2,5,3 }, {1,3,6 } };
double[] b = {8,14,20 };
// 分解系数矩阵A double[,] L = new double[3,3];
double[] D = new double[3];
CholeskyDecomposition(A, out L, out D);
// 求解方程组 double[] x = SolveEquation(L, D, b);
// 输出结果 Console.WriteLine("方程组的解为:");
for (int i =0; i < x.Length; i++)
{
Console.WriteLine("x" + (i +1) + " = " + x[i]);
}
}
// Cholesky分解 static void CholeskyDecomposition(double[,] A, out double[,] L, out double[] D)
{
int n = A.GetLength(0);
L = new double[n, n];
D = new double[n];
for (int i =0; i < n; i++)
{
double sum =0;
for (int k =0; k < i; k++)
{
sum += L[i, k] * L[i, k] * D[k];
}
D[i] = A[i, i] - sum;
for (int j = i; j < n; j++)
{
sum =0;
for (int k =0; k < i; k++)
{
sum += L[i, k] * L[j, k] * D[k];
}
L[j, i] = (A[j, i] - sum) / D[i];
}
}
}
// 求解方程组 static double[] SolveEquation(double[,] L, double[] D, double[] b)
{
int n = b.Length;
double[] y = new double[n];
double[] x = new double[n];
// 前代 for (int i =0; i < n; i++)
{
double sum =0;
for (int j =0; j < i; j++)
{
sum += L[i, j] * y[j];
}
y[i] = (b[i] - sum) / L[i, i];
}
// 后代 for (int i = n -1; i >=0; i--)
{
double sum =0;
for (int j = i +1; j < n; j++)
{
sum += L[j, i] * x[j];
}
x[i] = (y[i] - sum) / D[i];
}
return x;
}
}