用Python计算数组行列式的符号和自然对数
在这篇文章中,我们将介绍如何使用NumPy在Python中计算一个数组行列式的符号和自然对数。
numpy.linalg.slogdet() 方法
numpy.linalg.slogdet()方法提供我们在Python中计算数组行列式的符号和自然对数。如果一个数组的行列式非常小或非常大,对slogdet的调用可能会溢出或不足。因为它计算的是行列式的对数,而不是其本身的行列式,所以这个过程对这种问题更有抵抗力。
语法: numpy.linalg.slogdet()
参数:
- a: 类似数组的对象。输入的数组必须是一个二维数组。
返回:数组行列式的对数。
示例 1:
在这个例子中,使用numpy.array()方法创建了一个2维数组,numpy.lib.linalg.slogdet()被用来计算该数组行列式的对数和符号。该方法返回数组行列式的符号和对数。数组的形状、数据类型和尺寸可以通过.shape , .dtype , 和 .ndim属性找到。
# import packages
import numpy as np
# Creating an array
array = np.array([[10,20],[30,40]])
print(array)
# shape of the array is
print("Shape of the array is : ",array.shape)
# dimension of the array
print("The dimension of the array is : ",array.ndim)
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
# computing sign and natural logarithm of the
# determinant of the array
sign, determinant= (np.linalg.slogdet(array))
print('sign of the array is : '+str(sign))
print('logarithm of the determinant of the array is : '+ str(determinant))
输出:
[[10 20]
[30 40]]
Shape of the array is : (2, 2)
The dimension of the array is : 2
Datatype of our Array is : int64
sign of the array is : -1.0
logarithm of the determinant of the array is : 5.298317366548037
示例 2:
如果我们还想计算数组的行列式,我们可以使用sign*exp(logdet)并找到它。sign和logdet由numpy.lib.linalg.slogdet()方法返回。
import numpy as np
# Creating an array
array = np.array([[2,3],[5,6]])
print(array)
# shape of the array is
print("Shape of the array is : ",array.shape)
# dimension of the array
print("The dimension of the array is : ",array.ndim)
# Datatype of the array
print("Datatype of our Array is : ",array.dtype)
# computing sign and natural logarithm of the
# determinant of the array
sign, determinant= (np.linalg.slogdet(array))
print('sign of the array is : '+str(sign))
print('logarithm of the determinant of the array is : '+ str(determinant))
print('computing the determinant of the array using np.exp(): '
+ str(sign*np.exp(determinant)))
输出:
[[2 3]
[5 6]]
Shape of the array is : (2, 2)
The dimension of the array is : 2
Datatype of our Array is : int32
sign of the array is : -1.0
logarithm of the determinant of the array is : 1.0986122886681091
computing the determinant of the array using np.exp(): -2.9999999999999982