高斯消元法求解线性方程组

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");


01-05 5670

11-03 1.3万

11-05 4430

03-13 7121

08-21 628

09-20 370

08-02 1746

03-23 450

03-12 331

12-19 347