2017-03-03 147 views
2

我想在Python中實現simplex方法,所以我需要對數組使用高斯消元。經常會出現分數,爲了更加清晰和精確,我希望保留分數形式而不是使用浮點數。 我知道'分數'模塊,但我努力使用它。我使用這個模塊編寫了我的代碼,但數組總是返回浮動。是不是可以打印一個數組裏面的分數? 在這個簡單的例子:如何使用numpy數組與分數?

>>> A 
array([[-1., 1.], 
    [-2., -1.]]) 
>>> A[0][0]=Fraction(2,3) 
>>> A 
array([[ 0.66666667, 1.  ], 
    [-2.  , -1.  ]]) 

我想有array([[ 2/3, 1. ], [-2. , -1. ]])

似乎numpy的總是切換到浮

+2

如果你想確切有理數的矩陣工作,[sympy(http://docs.sympy.org/dev/tutorial/matrices.html)可能會更好地爲您服務。 – user2357112

+0

謝謝你的回答,但我不會使用sympy,因爲我已經用numpy開始了我的代碼。我不知道sympy,所以我記住下一個代碼! – Jkev

+0

我在矩陣上測試了sympy,它非常非常慢: https://stackoverflow.com/questions/45796747/are-sympy-matrices-really-that-slow – Wikunia

回答

1

由於Fraction s爲不是native NumPy dtype,到Fraction存儲在一個與NumPy陣列您需要convert the arrayobject dtype

import numpy as np 
from fractions import Fraction 

A = np.array([[-1., 1.], 
       [-2., -1.]]) # <-- creates an array with a floating-point dtype (float32 or float64 depending on your OS) 
A = A.astype('object') 
A[0, 0] = Fraction(2,3) 
print(A) 

打印

[[Fraction(2, 3) 1.0] 
[-2.0 -1.0]] 

PS。由於user2357112 suggests,如果你想使用有理數,你最好使用sympy。或者,僅將矩陣表示爲列表的列表。如果您的陣列的類型爲object dtype,則使用NumPy沒有速度優勢。

import sympy as sy 

A = [[-1., 1.], 
    [-2., -1.]] 
A[0][0] = sy.Rational('2/3') 
print(A) 

打印

[[2/3, 1.0], [-2.0, -1.0]] 
+0

謝謝你的回答,轉換數組正是我的需要。 – Jkev