C 语言高斯-约旦消元法

2024年8月28日 | 阅读 4 分钟

在本文中,我们将通过示例来讨论高斯-若尔当法

引言

高斯-若尔当法也被称为高斯-若尔当消元法。它是高斯消元法的一种改进版本,用于求解线性方程组

它与高斯消元法相比更简单,因为后者需要执行两个不同的过程,即:

  • 构建上三角矩阵
  • 回代求解

然而,对于高斯-若尔当消元法,我们只需要创建一个简化行阶梯形的对角矩阵。

使用高斯-若尔当法求解线性方程组的示例

输入

3x - 2y + z = 7

x + y + z = 2

2x - y - 3z = 1

输出

最终的增广矩阵为

1 0 0 1

0 1 0 2

0 0 1 3

结果是:x = 1, y = 2, z = 3

说明

在这个例子中,我们通过行运算将增广矩阵变换为行阶梯形,然后进一步变换为简化行阶梯形,从而使用高斯-若尔当法求解这个方程组。矩阵的最终形式使我们能够直接读出 x、yz 的解。

为了将增广矩阵转换为最终状态,我们使用了以下行运算

行2 = 行2 - 3 * 行1

行3 = 行3 - 2 * 行1

行1 = 行1 + 行2

行3 = 行3 + 行2

行1 = 行1 - 3 * 行3

行2 = 行2 - 2 * 行3

这些行运算得到了输出中显示的最终增广矩阵。矩阵最后一列显示了 x、yz 的值,分别是 1、23

以下是用于求解线性方程组的 C 语言程序源代码。该 C 程序可以成功编译。程序的输出也一并展示在下方。

代码

输出

Testcase Input:
Enter the number of variables: 4

Enter the equation1:
Enter the coefficient of x1: 2
Enter the coefficient of x2: 1
Enter the coefficient of x3: -3
Enter the coefficient of x4: 4
Enter the constant: 9

Enter the equation2:
Enter the coefficient of x1: 1
Enter the coefficient of x2: -2
Enter the coefficient of x3: 4
Enter the coefficient of x4: 3
Enter the constant: 7

Enter the equation3:
Enter the coefficient of x1: 3
Enter the coefficient of x2: 1
Enter the coefficient of x3: 5
Enter the coefficient of x4: -2
Enter the constant: 4

Enter the equation4:
Enter the coefficient of x1: 2
Enter the coefficient of x2: -5
Enter the coefficient of x3: 2
Enter the coefficient of x4: 1
Enter the constant: -6

Solutions:
THE VALUE OF x1 IS 1.000000
THE VALUE OF x2 IS 2.000000
THE VALUE OF x3 IS 3.000000
THE VALUE OF x4 IS -1.000000

说明

输入表示以下线性方程组

2x1 + x2 - 3x3 + 4x4 = 9

x1 - 2x2 + 4x3 + 3x4 = 7

3x1 + x2 + 5x3 - 2x4 = 4

2x1 - 5x2 + 2x3 + x4 = -6

该程序使用高斯-若尔当法求解该方程组,并为 x1、x2、x3x4 分别输出值 1.000000、2.000000、3.000000-1.000000。这些数值是该方程组的解,因为它们满足所有四个方程。这是对高斯-若尔当法的完整解释。