当前位置:   article > 正文

Python实现用初等行变换将矩阵化为最简行形式_python 初等行变换

python 初等行变换
import fractions

def row_echelon(A):
    """
    将矩阵A化为行阶梯矩阵
    """
    lead = 0
    rowCount = len(A)
    columnCount = len(A[0])
    for r in range(rowCount):
        if lead >= columnCount:
            return
        i = r
        while A[i][lead] == 0:
            i += 1
            if i == rowCount:
                i = r
                lead += 1
                if columnCount == lead:
                    return
        A[i], A[r] = A[r], A[i]
        lv = A[r][lead]
        A[r] = [fractions.Fraction(mrx, lv) for mrx in A[r]]
        for i in range(rowCount):
            if i != r:
                lv = A[i][lead]
                A[i] = [iv - lv*rv for rv,iv in zip(A[r],A[i])]
        lead += 1

# 定义一个3x3的矩阵
A = [
    [4,1,2],
    [13,-2,3],
    [0,3,2]
]


# 将矩阵化为行最简形式
row_echelon(A)

# 以分数形式打印结果
for row in A:
    print([str(fractions.Fraction(x).limit_denominator()) for x in row])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/479804
推荐阅读
相关标签
  

闽ICP备14008679号