我正在尝试创建一个程序,使用原始python代码和numpy数组来计算矩阵的行列式,以便与scipy进行比较功能。我的算法首先将矩阵转化为上三角,然后计算出最终的解。你知道吗
我可能发现了这个问题:所有的元素都是用整数计算的,这与浮点有一点不同一点点。然后呢,通过乘法效应,我得到了这样一个回答。但是我怎么修这个东西?在计算行元素时,仅仅加上float()
,出于某种原因,它们仍然是整数。你知道吗
def my_det(X):
'''
Parameters
----------
X : array_like
Returns
-------
det : float
Determinant of `a`.
Plan
----
Iterate through columns, create nested loop to iterate through all elements below
the main diagonal, assign a scaler according to the value, iterate through all
elements in the row to change them according to the scaler. Finally, compute
determinant.
'''
dimensionX, dimensionY = X.shape
if dimensionX == dimensionY:
matrixCopy = X.copy()
for i in range(dimensionX): # make only the diagonal non-zero
for getZero in range(i + 1, dimensionX): # make all elements below i-th zero(i.e. getZero elment = 0)
if matrixCopy[i, i] == 0: # cheating to create very small value
matrixCopy[i, i] == 1.0e-18
rowScaler = matrixCopy[getZero, i] / matrixCopy[i, i] # to change the rows accordingly
print(rowScaler)
for j in range(dimensionX): # change every element in the row
matrixCopy[getZero, j] = float(matrixCopy[getZero, j]) - float(rowScaler * matrixCopy[i, j])
print(matrixCopy[getZero, j])
print(matrixCopy)
det = 1.0
for detNum in range(dimensionX): # TADAAAAAAM
det *= matrixCopy[detNum, detNum]
return det
else:
print('ValueError: wrong dimensions')
# matrix = np.random.randint(50, size=(3, 3))
matrix = np.array([[39, 24, 16], [24, 45, 47], [2, 7, 28]])
# matrix = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]])
print(matrix)
print(my_det(matrix))
有两种标准方法可以将任意类似数组的输入转换为浮点数组。你知道吗
matrix_copy = X.astype(np.inexact, copy=True)
。这将通过所有浮点类型,并保证一个副本。这是您想要的选项,因为您需要数组的副本。你知道吗matrix_copy = np.asfarray(X)
。这将传递所有浮点类型,但如果数组已经是正确的类型,则不会复制数组。您不想使用此版本,因为它不会在所有情况下复制数据。你知道吗尝试改变
至
相关问题 更多 >
编程相关推荐