我有一個python代碼,我想從矩陣的兩個元素進行浮點除法。我嘗試了浮動()和從未來進口部門,但他們都沒有工作。這是我的代碼。python float division不起作用
from __future__ import division
import numpy as np
def backsub(U, b):
N = np.shape(U)[0]
x = b.copy()
x[N - 1, 0] = x[N - 1, 0]/U[N-1, N-1] #This keeps giving me integer results. No matter I do float(x[N - 1, 0]) or from __future__ import division
print x[N - 1, 0]
for i in range(N - 2, -1, -1):
for j in range(i + 1, N, 1):
x[i, 0] = x[i, 0] - U[i, j] * x[j]
x[i, 0] = x[i, 0]/U[i, i]
return x
b = np.matrix('1; 2; 3')
U = np.matrix('6, 5, 1; 0, 1, 7; 0, 0, 2')
print backsub(U, b)
輸出:
1
[[ 4]
[-5]
[ 1]]
您的矩陣實際上是否使用'dtype = float'?如果它們是'dtype = int',那麼在分配給它們之前你沒有做任何浮動操作將會有所幫助。 – Blckknght
你得到整數dtype的矩陣。創建時使用浮點數而不是整數。 – user2357112
我明白了。謝謝!有人可以發佈您的解決方案作爲答案,以便我可以接受嗎? – ZigZagZebra