2017-03-03 154 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