2015-11-06 136 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

我编辑答案让我知道,如果它有效或没有。 –