如何使用带分数的numpy数组? [英] How to use numpy arrays with fractions?
问题描述
我正在尝试在Python中实现单纯形方法,因此我需要在数组上使用高斯消除.通常会出现分数,为了更清楚,更准确地表示,我想保留分数形式而不是使用浮点数. 我知道分数"模块,但是我在努力使用它.我使用此模块编写了代码,但数组始终以浮点数返回.是否可以打印内部带有分数的数组? 在这个基本示例中:
I'm trying to implement the simplex method in Python so I need to use the Gaussian elimination on arrays. Very often fractions come up and for more clarity and precision I would like to keep the fractional form instead of using floats. I know the 'fractions' module but I'm struggling to use it. I wrote my code using this module but the arrays are always returned with floats. Isn't it possible to print an array with fractions inside ? On this basic example :
>>> 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. ]])
I would like to have array([[ 2/3, 1. ],
[-2. , -1. ]])
似乎numpy总是切换为浮点数
It seems numpy always switches to floats
推荐答案
由于Fraction
不是将数组转换为
Since Fraction
s are not a native NumPy dtype, to store a Fraction
in a NumPy array you need to convert the array to object
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建议,您最好使用如果您要使用有理数,请 sympy
.或者,仅将矩阵表示为列表列表.如果您的数组为object
dtype,则使用NumPy没有速度优势.
PS. As user2357112 suggests, you might be better off using sympy
if you wish to use rational numbers. Or, just represent the matrix as a list of lists. There are no speed advantages to using NumPy if your arrays are of object
dtype.
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]]
这篇关于如何使用带分数的numpy数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!