local Solve = function(tAb)
local Output = function()
local print = print;
for y=1,#tAb do
print(table.concat(tAb[y],"\t"));
end
print();
end
local Choose = function(b)
local L, V = b, tAb[b][b];
for l=b+1, #tAb do
if (tAb[l][b] > V) then
L, V = l, tAb[l][b];
elseif (-tAb[l][b] > V) then
L, V = l, tAb[l][b];
end
end
tAb[b], tAb[L] = tAb[L], tAb[b];
Output();
end
for b=1, #tAb-1 do
Choose(b);
local Lb = tAb[b];
for y=b+1, #tAb do
local Ly = tAb[y];
local d = Ly[b]/Lb[b];
for x=b, #Ly do
Ly[x] = Ly[x] - d * Lb[x];
end
Output();
end
Output();
end
--回算
local x = {};
for v=1,#tAb do
x[v] = 0;
end
for v=#tAb,1,-1 do
local Lv = tAb[v];
local S = Lv[#Lv];
for i=(v+1),(#Lv-1) do
S = S - (Lv[i] * x[i]);
end
x[v] = S / Lv[v];
end
return x;
end
local tA1 =
{
{1, 1, 1, 1, 10},
{2, 3, 1, 1, 15},
{3, -1, 2, -1, 3},
{4, 1, -3, 2, 5},
};
local tA2 =
{
{ 1, 2, -1, -3},
{ 4, 0, 1, 6},
{-1, 3, -2, -8},
};
local tA3 =
{
{2, 3,11, 5, 2},
{1, 1, 5, 2, 1},
{2, 1, 3, 2,-3},
{1, 1, 3, 3,-3},
};
local r,x = pcall(Solve,tA1);
print("\nx[] = \t" .. table.concat(x,"\t") .. "\n");
local r,x = pcall(Solve,tA2);
print("\nx[] = \t" .. table.concat(x,"\t") .. "\n");
local r,x = pcall(Solve,tA3);
print("\nx[] = \t" .. table.concat(x,"\t") .. "\n");
高斯消元法求解线性方程组
最新推荐文章于 2024-03-11 22:32:20 发布