using System;
namespace Zhou.CSharp.Algorithm
{
/// <summary>
/// 求解线性方程组的类 LEquations
/// 原作 周长发
/// 改编 深度混淆
/// </summary>
public static partial class LEquations
{
/// <summary>
/// 求解托伯利兹方程组的列文逊方法
/// </summary>
/// <param name="mtxLECoef">指定的系数矩阵</param>
/// <param name="mtxLEConst">指定的常数矩阵</param>
/// <param name="mtxResult">Matrix引用对象,返回方程组解矩阵</param>
/// <return>bool 型,方程组求解是否成功</return>
public static bool GetRootsetTlvs(Matrix mtxLECoef, Matrix mtxLEConst, Matrix mtxResult)
{
int i, j, k;
double a, beta, q, c, h;
// 未知数个数
int n = mtxLECoef.GetNumColumns();
// 初始化解解向量
mtxResult.Init(n, 1);
double[] x = mtxResult.GetData();
// 常数数组
double[] pDataConst = mtxLEConst.GetData();
// 建立T数组
double[] t = new double[n];
// 构造T数组
for (i = 0; i < n; ++i)
{
t[i] = mtxLECoef.GetElement(0, i);
}
// 临时数组
double[] s = new double[n];
double[] y = new double[n];
// 非托伯利兹方程组,不能用本方法求解
a = t[0];
if (Math.Abs(a) < float.Epsilon)
{
return false;
}
// 列文逊方法求解
y[0] = 1.0;
x[0] = pDataConst[0] / a;
for (k = 1; k <= n - 1; k++)
{
beta = 0.0;
q = 0.0;
for (j = 0; j <= k - 1; j++)
{
beta = beta + y[j] * t[j + 1];
q = q + x[j] * t[k - j];
}
if (Math.Abs(a) < float.Epsilon)
{
return false;
}
c = -beta / a;
s[0] = c * y[k - 1];
y[k] = y[k - 1];
if (k != 1)
{
for (i = 1; i <= k - 1; i++)
{
s[i] = y[i - 1] + c * y[k - i - 1];
}
}
a = a + c * beta;
if (Math.Abs(a) < float.Epsilon)
{
return false;
}
h = (pDataConst[k] - q) / a;
for (i = 0; i <= k - 1; i++)
{
x[i] = x[i] + h * s[i];
y[i] = s[i];
}
x[k] = h * y[k];
}
return true;
}
}
}