Python计算n阶行列式的值

本文将使用Python编写程序计算n阶行列式的值,不借助第三方库;

n阶行列式的定义

一个n阶行列式可以简单定义为:

Python求n阶行列式的值

其中 p1 p2 p3 ... pn 为自然数 1,2,...,n 的一个排列;t 为这个排列的逆序数;

计算n阶行列式

程序可计算1~n阶行列式:

def permute(nums):
    #生成n个元素的全排列
    length = len(nums)

    permutations = []

    def _permute(index=0):

        if index == length:
            permutations.append(nums[0:length])
        
        for i in range(index,length):
            nums[i],nums[index] = nums[index],nums[i]
            _permute(index+1)
            nums[i],nums[index] = nums[index],nums[i]
            
    _permute()

    return permutations


def inversion_number(nums):
    #计算排列的逆序数
    count = 0
    for i in range(len(nums)):

        for j in range(i):

            if nums[j] > nums[i]:

                count += 1

    return count

def calculate(det):
    #计算n阶行列式的值

    if not det:#没有元素
        return 0

    if len(det) == 1:#一阶行列式直接返回值
        return det[0]
    
    #生成 1,..., n的全排列
    permutations = permute([i for i in range(1,len(det)+1)])

    result = 0

    for p in permutations:
        #t为逆序数
        t = inversion_number(p)
        product = (-1)**t
        i = 0
        for pn in p:
            product *= det[i][pn-1] #连乘
            i+=1

        result += product #连加

    return result


A = []
A.append([1]) #1阶行列式
A.append(
    [
        [1,2],
        [3,4]
    ]) #2阶行列式

A.append(
    [
        [1,2,3],
        [4,5,6],
        [7,8,9]
    ]) #3阶行列式

for det in A:
    print("Input:")
    for i in det:
        print(i)
    print("value:",calculate(det),"\n")

运行效果

Input:
1
value: 1

Input:
[1, 2]
[3, 4]
value: -2

Input:
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
value: 0

原创内容,如需转载,请注明出处;

本文地址: https://www.perfcode.com/p/the-nth-order-determinant-in-python.html

分类: 计算机技术
推荐阅读:
Python bool()函数 在 Python 中,bool() 是一个内置函数,用于将一个值转换为 bool 类型。bool() 函数返回两个值之一:True 或 False。
Python int()函数 在Python中,int()函数用于将一个数值或字符串转换为整数。如果提供了一个字符串作为参数,那么int()函数将尝试将该字符串解释为一个整数,并返回对应的整数值。如果字符串无法解释为整数,则会引发ValueError异常。
Python all()函数详细教程 all()函数只接受一个可迭代的类型参数;如果该迭代器的所有元素为True或该迭代器为空,则返回True,否则返回False;
在Python中如何表示无穷大 在Python中,可以使用float('inf')表示正无穷大,使用float('-inf')表示负无穷大。
xxxx is not in the sudoers file. This incident will be reported. 解决方法 使用sudo命令时出现xxxx is not in the sudoers file. This incident will be reported. 这里的xxxx是你的用户名;出现这个提示通常是用户名没有写入到sudoers文件中;
Pyside6 allWidgets()函数详细教程 PySide6.QtWidgets.QApplication类的成员函数allWidgets()用于返回一个包含所有小部件对象的列表;