2015-11-06 118 views
1

我有一個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]] 
+1

您的矩陣實際上是否使用'dtype = float'?如果它們是'dtype = int',那麼在分配給它們之前你沒有做任何浮動操作將會有所幫助。 – Blckknght

+1

你得到整數dtype的矩陣。創建時使用浮點數而不是整數。 – user2357112

+0

我明白了。謝謝!有人可以發佈您的解決方案作爲答案,以便我可以接受嗎? – ZigZagZebra

回答

2

嘗試

x[i, 0] = float(x[i, 0])/U[i, i] 

試試看

b = np.matrix('1; 2; 3', dtype=float) 
U = np.matrix('6, 5, 1; 0, 1, 7; 0, 0, 2', dtype=float) 

,或者您也可以嘗試

b = np.matrix([[1], [2], [3], dtype=float) 
U = np.matrix([[6, 5, 1], [0, 1, 7], [0, 0, 2]], dtype=float) 

希望它可以幫助你。

+0

仍然無法正常工作。 :(問題是x [N - 1,0] = x [N - 1,0]/U [N - 1,N - 1]應該是浮動。不知道如何解決它。 – ZigZagZebra

+0

我編輯答案讓我知道,如果它有效或沒有。 –