![](/img/trans.png)
[英]In Python, why does the lowest (smallest) floating point value have different significant-digits than the largest?
[英]Why array have different value than anticipated?
我將 class 的屬性從:
self.firstBase = np.array([1, 0])
self.secondBase = np.array([0, 1])
至
self.base = np.array([[1, 0], [0, 1]])
從那時起,將這兩個向量乘以 Hadamard 矩陣的操作返回錯誤值。
def H(self):
H = np.array([[1 / math.sqrt(2), 1 / math.sqrt(2)],
[1 / math.sqrt(2), - 1 / math.sqrt(2)]])
topValue = H[0][0] * self.base[0][0] + H[0][1] * self.base[0][1]
bottomValue = H[1][0] * self.base[0][0] + H[1][1] * self.base[0][1]
self.base[0] = np.array([topValue, bottomValue])
topValue = H[0][0] * self.base[1][0] + H[0][1] * self.base[1][1]
bottomValue = H[1][0] * self.base[1][0] + H[1][1] * self.base[1][1]
self.base[1] = np.array([topValue, bottomValue])
return self
我做了一些測試,發現計算仍然正確,但是當我初始化時
self.base[0] = np.array([topValue, bottomValue])
和
self.base[1] = np.array([topValue, bottomValue])
結果它給了我 [0, 0] 和 [0, 0] 。
這是為什么? 解決方法是什么?
self.base
數據類型更改為float
self.base = np.array([[1, 0], [0, 1]], dtype=float)
發生這種情況是因為您試圖將浮點值分配給 integer 數組。 因此,需要使用浮點值來初始化self.base
,如下所示:
self.base = np.array([1.0, 0.0], [0.0, 1.0])
self.base = np.array([[1, 0], [0, 1]], dtype=float)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.