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

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");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值