function gaussJordan(matrix, constants)
local n = #matrix
for i = 1, n do
-- 寻找最大的元素作为主元
local max = i
for j = i + 1, n do
if math.abs(matrix[j][i]) > math.abs(matrix[max][i]) then
max = j
end
end
-- 如果主元是0,则无解或者无限多解
if matrix[max][i] == 0 then
--自行处理
end
-- 交换行使得绝对值最大的元素处于对角线上
matrix[i], matrix[max] = matrix[max], matrix[i]
constants[i], constants[max] = constants[max], constants[i]
-- 归一化当前行,并确保对角线元素为1
local diag = matrix[i][i]
for j = 1, n do
matrix[i][j] = matrix[i][j] / diag
end
constants[i] = constants[i] / diag
-- 消除当前列的其他行
for k = 1, n do
if k ~= i then
local factor = matrix[k][i]
for l = 1, n do
matrix[k][l] = matrix[k][l] - factor * matrix[i][l]
end
constants[k] = constants[k] - factor * constants[i]
end
end
end
return constants
end
-- 系数矩阵
local matrix = {
{8, 2, 3, 3, 1},
{1, 2, 2, 2, 10},
{0.1, 2, 0.2, 0.2, 0.1},
{0.1, 0.2, 2, 0.2, 0.1},
{0.1, 0.2, 0.2, 2, 0.1}
}
-- 常数向量
local constants = {30000, 5000, 1000, 500, 300}
-- 解方程组
local solutions = gaussJordan(matrix, constants)
-- 输出结果
print("a =", solutions[1])
print("b =", solutions[2])
print("c =", solutions[3])
print("d =", solutions[4])
print("e =", solutions[5])