计算方法实验2(补充):列主元消元法解线性方程组

C++源代码

cpp 复制代码
#include<bits/stdc++.h>
using namespace std;

// 列主元消去法求解线性方程组
vector<long double> Column_Elimination(vector<vector<long double>> A, vector<long double> b);

int main()
{
    vector<vector<long double>> A(3, vector<long double>(3, 0));
    A[0][0] = 2, A[0][1] = 4, A[0][2] = -3;
    A[1][0] = 4, A[1][1] = -3, A[1][2] = 1;
    A[2][0] = 1, A[2][1] = 3, A[2][2] = -2;
    vector<long double> b(3, 1);
    vector<long double> X = Column_Elimination(A, b);
    for(int i = 0; i < 3; i++)
        cout << X[i] << " ";
    return 0;
}

// 列主元消去法求解线性方程组
vector<long double> Column_Elimination(vector<vector<long double>> A, vector<long double> b)
{
    int n = A.size();
    vector<long double> x(n, 0);
    vector<vector<long double>> matrix(n, vector<long double>(n + 1, 0));

    for(int i = 0; i < n; i++)
    {
        matrix[i][n] = b[i];
        for(int j = 0; j < n; j++)
            matrix[i][j] = A[i][j];
    }
        
    for(int col = 0; col < n; col++)//找到列主元
    {
        long double maxnum = abs(matrix[col][col]);
        int maxrow = col;
        for(int row = col + 1; row < n; row++)
        {
            if(abs(matrix[row][col]) > maxnum)
            {
                maxnum = abs(matrix[row][col]);
                maxrow = row;
            }
        }
        swap(matrix[col], matrix[maxrow]);
        for(int row = col + 1; row < n; row++)
        {
            long double res = matrix[row][col] / matrix[col][col];
            for(int loc = col; loc <= n; loc++)
                matrix[row][loc] -= matrix[col][loc] * res; 
        }
    }
    for(int row = n - 1; row >= 0; row--)//回代
    {
        for(int col = row + 1; col < n; col++)
        {
            matrix[row][n] -= matrix[col][n] * matrix[row][col] / matrix[col][col];
            matrix[row][col] = 0;
        }
        matrix[row][n] /= matrix[row][row];
        matrix[row][row] = 1;
    }
    for(int i = 0; i < n; i++)
        x[i] = matrix[i][n];
    return x;
}

补充:python解线性方程组

python 复制代码
import numpy as np

A = np.array([[2, 4, -3], [4, -3, 1], [1, 3, -2]])
b = np.array([1, 1, 1])

x = np.linalg.solve(A, b)

print(x)
相关推荐
lxh011320 分钟前
螺旋数组题解
前端·算法·js
2***B44921 分钟前
C++在金融中的QuantLibXL
开发语言·c++·金融
A***071735 分钟前
C++在游戏中的阴影渲染
开发语言·c++·游戏
czlczl200209251 小时前
算法:二叉树的公共祖先
算法
Salt_07281 小时前
DAY 19 数组的常见操作和形状
人工智能·python·机器学习
无心水2 小时前
【Python实战进阶】2、Jupyter Notebook终极指南:为什么说不会Jupyter就等于不会Python?
python·jupyter·信息可视化·binder·google colab·python实战进阶·python工程化实战进阶
Q***l6872 小时前
C++在计算机图形学中的渲染
开发语言·c++
稚辉君.MCA_P8_Java2 小时前
Gemini永久会员 Java动态规划
java·数据结构·leetcode·排序算法·动态规划
oioihoii2 小时前
C++语言演进之路:从“C with Classes”到现代编程基石
java·c语言·c++
小白程序员成长日记2 小时前
2025.11.23 力扣每日一题
算法·leetcode·职场和发展