[英]Cannot add matrices more than 20 times in loop
我試圖在for循環中創建2x2矩陣的總和,但是當我將總和循環超過21次(當我的n> 20時,如下所示)時,它會給我以下錯誤消息:
TypeError:根據轉換規則``same_kind'',ufunc'add'輸出(typecode'O')不能被強制為提供的輸出參數(typecode'd')
這是我的代碼:
k = 2
n = 21
A2 = np.matrix('0.5 -0.5; 0.5 0.5')
SumA2 = np.zeros((k,k))
for i in range(0, n+1):
SumA2 += np.linalg.matrix_power(A2, i)/np.math.factorial(i)
print(A2)
print("\n", SumA2)
我懷疑這與階乘過大有關,但是這真的是一個問題嗎? 在Matlab中,我可以循環1000次而不會出現問題。
在21,它將數組類型切換為object:
In [776]: np.linalg.matrix_power(A2,20)/np.math.factorial(20)
Out[776]:
matrix([[-4.01398205e-22, 0.00000000e+00],
[ 0.00000000e+00, -4.01398205e-22]])
In [777]: np.linalg.matrix_power(A2,21)/np.math.factorial(21)
Out[777]:
matrix([[-9.557100128609015e-24, 9.557100128609015e-24],
[-9.557100128609015e-24, -9.557100128609015e-24]], dtype=object)
更具體地說,它是轉換的factorial
:
In [778]: np.array(np.math.factorial(20))
Out[778]: array(2432902008176640000)
In [779]: np.array(np.math.factorial(21))
Out[779]: array(51090942171709440000, dtype=object)
Python3將整數用於factorial
。 這些可以是任何長度。 但是在這一點上,該值變得太大而無法用np.int64
表示。 因此,它切換為使用包含長Python整數的對象dtype數組。 該開關傳播到power
計算。
當它嘗試將此數組轉換為與SumA2
兼容的SumA2
時,將出現錯誤。
In [782]: SumA2 = np.zeros((k,k))
In [783]: SumA2 += Out[777]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-783-53cbd27f9514> in <module>()
----> 1 SumA2 += Out[777]
TypeError: ufunc 'add' output (typecode 'O') could not be coerced to provided output parameter (typecode 'd') according to the casting rule ''same_kind''
In [784]: SumA2 = np.zeros((k,k), object)
In [785]: SumA2 += Out[777]
In [786]: SumA2
Out[786]:
array([[-9.557100128609015e-24, 9.557100128609015e-24],
[-9.557100128609015e-24, -9.557100128609015e-24]], dtype=object)
在170,它開始遇到將整數轉換為浮點數的問題
首先做1/factorial(...)
似乎有幫助。 並將A2
的dtype更改為更高精度的float可能會有所幫助:
In [812]: np.linalg.matrix_power(A2.astype('float128'),171)*(1/np.math.factorial(171))
Out[812]:
matrix([[-1.04145922e-335, -1.04145922e-335],
[ 1.04145922e-335, -1.04145922e-335]], dtype=float128)
對於2x2矩陣,這實際上並沒有特別使用numpy
。 使用列表和“原始” Python數字幾乎可以很容易地計算出重復功效。 但是,即使那些不是為無限精度數學而設計的。 整數可能很長,但我認為Python浮點數沒有那么靈活。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.