python输出高斯消元法求解行列式的过程

2023-10-28

前言

有人可能好奇,为啥有那么多工具还要自己写一个。emmm…
比如我求 Ax=b, 增广矩阵, 比如说我想要 [ A , I ] [A, I] [A,I] -> [ I , A − 1 ] [I, A^{-1}] [I,A1], 工具就用不了了
该代码会被我另一篇博客用到 矩阵分析课后题部分题目之计算机辅助(python)

这个代码的作用



代码

echelon_form.py

"""
支持分数,主要用来计算阶梯型和最简阶梯型, 行列式, 矩阵的逆, 克拉默求解x
Ax = b
Alter time: 2022.9.25 17:19
"""
from fractions import Fraction
import copy


cnt = 0  # 步骤计数器
det_cof = 1  # 经过行变换导致行列式的变化(乘上这个就不变)


# frac.numerator 整数/ frac.denominator分数
# 创造一个支持分数运算的矩阵
def make_matrix(list_matrix):
    global cnt
    global det_cof
    cnt = 0
    det_cof = 1

    fra_matrix = []
    for i in range(len(list_matrix)):
        row = []
        for j in list_matrix[i]:
            if not isinstance(j, Fraction):
                row.append(Fraction(j))
            else:
                row.append(j)
        fra_matrix.append(row)
    show(fra_matrix, 'process {}. former matrix:'.format(cnt))
    return fra_matrix


# 自动增加单位矩阵的 “增广”矩阵, 主要是为了求逆
def make_A_I_matrix(a):
    assert len(a) == len(a[0]), 'len(a) != len(a[0])'
    n = len(a)
    for row in range(n):
        for col in range(n):
            if (row == col):
                a[row].append(1)
            else:
                a[row].append(0)
    return make_matrix(a)


# 展示矩阵
def show(matrix, information_str='no tips', show_procedure=True, cal_det=False):
    global cnt
    if show_procedure:
        print(information_str)
        print('-' * len(matrix[0]) * 10)
        for row in matrix:
            for item in row:
                print('{:>10}'.format(str(item)), end='')
            print()
        if cal_det:
            print('and the cofficient before the det(A) after the row operation is {}|A|'.format(
                det_cof
            ))
        print()
    cnt += 1


# 交换两行 (行数下标从1开始, 即 m * n的矩阵, 行数下标从1 ~ m)
def change_row(matrix, row1_num, row2_num, show_procedure, cal_det=False):
    global cnt
    global det_cof
    matrix[row1_num],  matrix[row2_num] = matrix[row2_num], matrix[row1_num]
    det_cof *= -1    # 交换两行,行列式改变符号
    show(matrix, 'process {}. change row {} and row {}'.format(cnt, row1_num, row2_num), show_procedure, cal_det)


# 化简某一行 (行数下标从0开始, 即 m * n的矩阵, 行数下标[0, m-1] )
def simplify(matrix, row_num, pivot_col, reduce_echelon_form=False, show_procedure=True, cal_det=False):
    global cnt
    global det_cof
    # row_num -= 1
    pivot = matrix[row_num][pivot_col]
    for j in range(len(matrix[0])):
        matrix[row_num][j] /= pivot
    det_cof *= pivot    # 某一行除以多少就要乘回来

    # 化简为 最简行列式
    if reduce_echelon_form:
        for i in range(len(matrix)):
            if i != row_num:
                times = matrix[i][pivot_col]
                for j in range(len(matrix[0])):
                    matrix[i][j] -= matrix[row_num][j] * times
    else: # 只是化为行列式
        for i in range(row_num + 1, len(matrix)):
            times = matrix[i][pivot_col]
            for j in range(len(matrix[0])):
                matrix[i][j] -= matrix[row_num][j] * times
    show(matrix, 'process {}. simplify row {}'.format(cnt, row_num), show_procedure, cal_det)


# 化为阶梯型
def echelon_form(a, cc_num=None, reduce_echelon_form=False, cal_det=False, show_procedure=True):
    m, n = len(a), len(a[0])
    # print('s001: ', m, n, cofficient_cols_num)

    if cc_num is None:
        cc_num = n

    prc_row, prc_col = 0, 0
    while prc_row < m and prc_col < cc_num:
        if a[prc_row][prc_col] == 0:
            zero_flag = True
            for f_row in range(prc_row + 1, m):
                if a[f_row][prc_col] != 0:
                    change_row(a, prc_row, f_row, show_procedure, cal_det)
                    zero_flag = False
                    break
            if zero_flag:
                prc_col += 1
                continue
        if show_procedure:
            print('prc_row, prc_col:', prc_row, prc_col)
        simplify(a, prc_row, prc_col, reduce_echelon_form=reduce_echelon_form,
         show_procedure=show_procedure, cal_det=cal_det)
        prc_row += 1
        prc_col += 1
    
    tips_op = '(reduced)' if reduce_echelon_form else ''

    if prc_row == m and prc_col == cc_num:
        print('The matrix has been changed to {} echelon form'.format(tips_op))
    else:
        print('The matrix is singular')

    if cal_det:
        if len(a) != len(a[0]):
            "you're trying to cal a det of matrix, but this matrix is not square matrix"
            return 'error'
        if prc_row == m and prc_col == cc_num:
            det_result = det_cof
            for i in range(0, m):
                det_result *= a[i][i]
                if det_result == 0:
                    break
            print('the det of this matrix is {}.'.format(det_result))
        else:
            print('Because the matrix is singualr, so its det is 0.')
        return det_result


# 通过Guass-Jordon方法求逆
def cal_inv_by_guass_jordan(a):
    cofficient_cols_num = len(a[0])

    a = make_A_I_matrix(a)
    
    echelon_form(a, cofficient_cols_num, reduce_echelon_form=True,
     cal_det=False, show_procedure=True)


# 将A的某一行进行替换
def replace_A_by_b_at_col_i(a, b, col_i):
    r = copy.deepcopy(a)
    for row in range(len(a)):
        r[row][col_i] = b[row]
    return r


# 使用克拉默计算
def cal_x_by_Cramer(a, b):
    x_lt = []
    cofficient_cols_num = len(a)
    ma = make_matrix(a)
    x_lt.append(echelon_form(ma, cofficient_cols_num, reduce_echelon_form=False,
     cal_det=True, show_procedure=False))
    if x_lt[0] == 'error':
        raise Exception('cal det error')
    
    for col in range(len(a[0])):
        a_im1 = replace_A_by_b_at_col_i(a, b, col)
        ma = make_matrix(a_im1)
        x_lt.append(echelon_form(ma, cofficient_cols_num, reduce_echelon_form=False,
        cal_det=True, show_procedure=False))

    print('\n------ Cramer result ------')
    print('det(A) = {}'.format(x_lt[0]))
    for i in range(1, len(x_lt)):
        print('det(A_{}) = {}, x_{} = ({}) / ({}) = {}'.format(
            i, x_lt[i], i, x_lt[i], x_lt[0], round(float(x_lt[i]) / float(x_lt[0]), 2)))
    print('------ Cramer end ------')


def matrix_mul(a, b, show_result=True):
    r1, c1 = len(a), len(a[0])
    r2, c2 = len(b), len(b[0])
    assert c1 == r2, 'the col of matrix a is not equal to the row of matrix b'

    result = [[0 for col in range(c2)] for row in range(r1)]

    for i in range(r1):
        for j in range(c2):
            for k in range(c1):
                result[i][j] += a[i][k] * b[k][j]
    
    print('-' * c2 * 4)
    for row in range(r1):
        for col in range(c2):
            print('{}'.format(result[row][col]))
    print('-' * c2 * 4)
    return result


if __name__ == '__main__':
    a = [[1, 2, 1, 3], [2, 5, -1, -4], [3, -2, -1, 5]]
    a = make_matrix(a)
    cnt = 0  # 步骤计数器

    cofficient_cols_num = 3

    echelon_form(a, cofficient_cols_num, reduce_echelon_form=True, cal_det=False)

例子(chapter 1, question 23 (a)题)输出:

process 0. former matrix:
----------------------------------------
         1         2         1         3
         2         5        -1        -4
         3        -2        -1         5

prc_row, prc_col: 0 0
process 0. simplify row 0
----------------------------------------
         1         2         1         3
         0         1        -3       -10
         0        -8        -4        -4

prc_row, prc_col: 1 1
process 1. simplify row 1
----------------------------------------
         1         0         7        23
         0         1        -3       -10
         0         0       -28       -84

prc_row, prc_col: 2 2
process 2. simplify row 2
----------------------------------------
         1         0         0         2
         0         1         0        -1
         0         0         1         3
The matrix has been changed to (reduced) echelon form



如果最后一行代码改一下, 即reduce_echelon_form为False, 我们只想得到阶梯型

echelon_form(a, cofficient_cols_num, reduce_echelon_form=False)

输出:

process 0. former matrix:
----------------------------------------
         1         2         1         3
         2         5        -1        -4
         3        -2        -1         5

prc_row, prc_col: 0 0
process 0. simplify row 0
----------------------------------------
         1         2         1         3
         0         1        -3       -10
         0        -8        -4        -4

prc_row, prc_col: 1 1
process 1. simplify row 1
----------------------------------------
         1         2         1         3
         0         1        -3       -10
         0         0       -28       -84

prc_row, prc_col: 2 2
process 2. simplify row 2
----------------------------------------
         1         2         1         3
         0         1        -3       -10
         0         0         1         3
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python输出高斯消元法求解行列式的过程 的相关文章

  • Marriage is Stable

    http acm hdu edu cn showproblem php pid 1522 Problem Description Albert Brad Chuck are happy bachelors who are in love w
  • JVM--三大子系统详解

    首先需要了解java的命令 javac 将java文件编译为 class文件 里面是一些二进制文件 javap c 将 class文件变为反汇编 例如 javap c hello class gt demo txt 可以将class文件转化
  • GPIO介绍

    目录 一 GPIO是什么 二 STM32引脚分类 三 GPIO内部结构 四 GPIO的工作模式 4 1 输入模式 模拟 上拉 下拉 浮空 4 2 输出模式 推挽 开漏 4 3 复用功能 推挽 开漏 4 4 模拟输入输出 上下拉无影响 一 G
  • c语言将csv文件存储到数组,读取CSV文件并将值存储到数组中

    青春有我 我最喜欢的CSV解析器是一个内置在 NET库中的解析器 这是Microsoft VisualBasic命名空间中隐藏的宝藏 下面是一个示例代码 using Microsoft VisualBasic FileIO var path
  • ConcurrentHashMap 的实现原理

    目录 常见问题 1 concurrentHashMap特点 2 concurrentHashMap如何保证效率高 又安全的 1 构造函数 2 put方法 2 1 initTable 2 2 addCount方法 3 get方法 常见问题 1
  • 【SpinalHDL】Windows10系统搭建SpinalHDL 开发环境

    本文主要记载如何从零开始在win平台搭建SpinalHDL开发环境并跑通第一个spinal project demo 1 环境准备 1 1 软件下载 首先列出需要安装的软件 并逐一对这些软件的功能和其必要性进行说明 需要安装的软件 IDEA
  • 继电器的过流过压保护(自恢复保险丝)

    简述 继电器广泛应用于消费电子产业和工业设备中 它具有控制系统 又称输入回路 和被控制系统 又称输出回路 它实际上是用较小的电流去控制较大电流的一种 自动开关 故在电路中起着自动调节 安全保护 转换电路等作用 继电器可能因为过流或者过压而损
  • arduino/mixly TFT显示SD卡的图片

    一 器材 SD卡模块 1 8寸TFT屏 ST7735 arduino uno开发板 SD卡 二 接线 TFT屏 arduino uno GND GND VCC 5V SCL D13 SDA D11 RES D8 DC D10 CS D9 B
  • Java锁机制

    Java锁主要是为了解决线程安全问题 当多个线程共享同一个变量时可能会出现同时修改变量的情况 这样会导致最终计算结果错误 未解决该问题 Java提供了各种锁来确保数据能够被正常修改和访问 最常用的比如synchronized 一 互斥同步
  • python计算机视觉学习第三章——图像到图像的映射

    目录 引言 一 单应性变换 1 1 直接线性变换算法 1 2 仿射变换 二 图像扭曲 2 1 图像中的图像 2 2 分段仿射扭曲 2 2 图像配准 三 创建全景图 3 1 RANSAC 随机一致性采样 3 2 拼接图像 四 总结 引言 本章
  • [4G&5G专题-119]:5G培训应用篇-4-5G典型行业应用的解决方案(车联网、智慧医疗、智能教育、智能电网)

    目录 前言 前言 1 总目录 前言 2 本章 第1章 5G行业应用介绍 第2章 车联网解决方案 2 1 车联网概述 2 2 车联网需求分析 2 3 车联网解决方案 第3章 智慧医疗解决方案 第4章 智能教育解决方案 第5章 智能电网解决方案
  • Mybatis配置多数据源

    前言 Spring Boot项目使用Mybatis 既要从上游系统同步数据 又要操作本系统的数据库 所以需要引入双数据源 配置Mybatis 步骤 一 配置双数据源 连接数据库 1 禁用Spring Boot数据源的自动装配 在启动类 Sp
  • 请求调页存储管理方式的模拟 含详细代码和实验结果截图

    请求调页存储管理方式的模拟 实验目的 通过对页面 页表 地址转换和页面置换过程的模拟 加深对请求调页系统的原理和实现过程的理解 实验内容 假设每个页面中可存放10条指令 分配给一作业的内存块数为4 用C语言模拟一作业的执行过程 该作业共有3
  • 为什么Hadoop集群中机器台数多反而执行速度慢?

    这里我对这个现象给出解释 由于水平有限 发现错误 请及时留言 或站内和我联系 这里假设集群中有slave1 slave2 slave3三个节点 其中slave3工作效率低 一共有6个任务 需要去做 slave1和slave2执行一个任务是1
  • 104个精选计算机毕业设计项目,助你制作出色的程序,一定要试试

    对于即将面临毕业设计的计算机专业的同学们 如何选题和完成毕设项目成为一个重要而又棘手的问题 今天给大四的同学分享毕业设计项目 希望对正在为毕业设计发愁的小伙伴有帮助 一 成品列表 以下所有springboot框架项目的源码博主已经打包好上传
  • rpmbuild制作包的详细过程

    https www cnblogs com schangech p 5641108 html https www ibm com developerworks cn linux l rpm 一 目录结构生成 1 工具安装rpmdevtool
  • STM32之中断和事件

    中断和事件 什么是中断 当CPU正在执行程序时 由于发生了某种事件 要求CPU暂时中断当前的程序执行 转而去处理这个随机事件 处理完以后 再回到原来被中断的地方 继续原来的程序执行 这样的过程称为中断 什么是事件 当检测到某一个动作的触发
  • 内网 centos7 离线安装rpm包的三种方法

    一 使用 downloadonly参数 此种方法的优点是下载的rpm包可以下载至同一目录中 一 互联网电脑下载rpm包 1 查看互联网电脑是否支持 只下载不安装 功能 执行yum帮助命令 yum help 如果列表中出现 downloado
  • 文件操作之文件包含全解(31)

    文件包含的作用就是将这个文件包含进去之后 会调用指定文件的代码 先将文件包含才能执行里面的一些相关代码 比如所想进行文件的链接 数据库的查询 就可以先包含一个数据库的配置文件 再去链接的话就享有配置文件的一些配置信息 就不需要在进行相关的操
  • stegsolve图片隐写解析器的使用

    layout post title ctf 隐写图片解析器 stegsolve的使用 categories ctf tags stegsolve CTF隐写术 隐写图片解析神器 stegsolve stegsolve下载地址 http ww

随机推荐

  • 静态测试和动态测试相关知识点

    目 录 知识总结 5 第一章 5 第二章软件测试基础 5 第三章基于生命周期的软件测试 6 第四章软件测试的分类 6 第五章软件缺陷管理 6 第六章软件测试过程及其管理 7 静态测试 7 1
  • ubunt 上进行c++ cuda编程

    目录 概述 cmake代码 头文件代码 头文件对应的cuda代码实现 c 的代码 运行结果 参考资料 概述 首先先通过一个简单的demo来演示cuda编程是怎么进行的 cmake代码 cmake minimum required VERSI
  • 替换docker容器中的文件

    bin bash 宣告文件内的语法使用bash语法 于是当程序执行时 加载bash的相关环境配置文件 在shell脚本中 倒引号 括起来的表示要执行的命令 dirname 0 获取当前shell程序的路径 cd dirname 0 进入当前
  • ES6中const的使用

    const声明一个只读的常量 一旦声明 常量的值就不能改变 且const一旦声明变量 就必须立即初始化 不能留到以后赋值 const的作用域与let命令相同 只在声明所在的块级作用域内有效 const命令声明的常量也是不提升 同样存在暂时性
  • 目标检测:划分数据集,生成ImageSets\Main下的txt文档

    coding utf 8 Time 2020 6 1 Author WangKaiNing File xml2voc py import os import random 可能需要修改的地方 g root path D AAAAA bigd
  • Linux报错:tar: Error Is Not Recoverable: Exiting Now

    Linux操作系统下 下载完成xx tar gz文件然后执行tar zxvf xx tar gz 执行出现如下错误 xxx tar gz 归档文件中异常的 EOF tar 归档文件中异常的 EOF tar Error is not reco
  • 「ML 实践篇」分类系统:图片数字识别

    目的 使用 MNIST 数据集 建立数字图像识别模型 识别任意图像中的数字 文章目录 1 数据准备 MNIST 2 二元分类器 SGD 3 性能测试 1 交叉验证 2 混淆矩阵 3 查准率与查全率 4 P R 曲线 5 ROC 曲线 6 R
  • ActiveX控件开发、部署、使用(全)

    本文基于MFC的ActiveX控件开发 很大程度上和基于ALT的ActiveX控件编写有相同之处 首先创建基于MFC的ActiveX控件 OK一路下一步 完成 添加与外部接口 ClassView Lib Events ADD method
  • 51单片机c语言dac0832产生波形,单片机控制DAC0832产生各种波形Proteus仿真程序

    include sbit wr P3 6 sbit rd P3 2 sbit key0 P1 0 定义P1 0脚的按键为正弦波键key0 sbit key1 P1 1 定义P1 1脚的按键为方波键key1 sbit key2 P1 2 定义
  • Kafka 面试套路居然这样多!读完大神的 Kafka 核心手册,秒杀面试官!全网最强!!

    在热招的 Java 架构师岗位面试中 Kafka 面试题被面试官选中的几率非常大 也是 HR 的杀手锏和狠招 一般来讲 面试题有以下几种 Kafka 为什么这么快 如何对 Kafka 集群进行调优 Kafka 的高性能网络架构是如何设计的
  • 【JavaScript】详解JavaScript中的replace()函数

    replace 1 方法简介 2 replace 使用 2 1 replace 字符串 字符串 2 2 replace 正则表达式 字符串 2 3 replace 正则表达式 function 2 3 1 简单用法 正则表达式不使用分组 2
  • QString 和char *和QByteArray的转换总结

    参考博客 https www cnblogs com findumars p 5107700 html 以下内容摘抄以上大神博客 1 char转换为QString char a b QString str str QString a 2 Q
  • 为 openEuler 安装 桌面环境图形化界面【ukui】

    三 UKUI 图形化界面 3 1 安装图形化界面 ukui 由于openEuler只有命令行操作界面 所以我们可以给openEuler安装一个桌面图形环境 最近华为发布了一个适用于openEuler的图形化界面 叫作UKUI 3 1 1 首
  • C++调用python脚本

    C 调用python的脚本 一 为什么 缘由 用python写了机器学习的模型 项目工程代码是C 写得 所以在调用时 想通过C 调用python脚本 用c 获取返回值 然后就是一个接着一个的坑 二 环境 环境win10 64 VS2008
  • 虚拟机中如何挂载物理磁盘(VMware操作)

    虚拟机中如何挂载物理磁盘 VMware操作 来源 本站转载 作者 佚名 时间 2012 04 16 11 05 04 测试的时候难免会遇到 从真是机器拷贝东西到虚拟机中 虽说安装了VMware tools Vm Install VMware
  • 关于Mybatis中的条件查询。createCriteria example里面的条件

    之前用Mybatis框架反向的实体 还有实体里面的Example 之前只是知道Example里面放的是条件查询的方法 可以一直不知道怎么用 到今天才开始知道怎么简单的用 在我们前台查询的时候会有许多的条件传过来 先看个例子 public L
  • linux内核分析编译体验

    一 资源 linux 2 6 22 6 下载地址 https mirrors edge kernel org pub linux kernel v2 6 linux 2 6 22 6 jz2440 patch下载地址 https downl
  • cesium简介

    文章目 1 什么是Cesium 2 Cesium能做什么 3 Cesium的依赖性 4 Cesium学习参考 Cesium实战系列文章总目录 传送门 1 什么是Cesium Cesium是AGI公司计算机图形开发小组与2011年研发的三维地
  • ant-design-vue customRequst

    关于a upload中customRequest customRequest回调参数 onProgress event percent number void onError event Error body Object void onS
  • python输出高斯消元法求解行列式的过程

    前言 有人可能好奇 为啥有那么多工具还要自己写一个 emmm 比如我求 Ax b 增广矩阵 比如说我想要 A I A I A I gt