python - 在 Python 的 Fraction 模块中使用 numpy 向量元素

标签 python numpy fractions

我正在尝试使用 numpy 数组中的元素作为 Fraction 模块的输入,但出现以下错误:“TypeError: both arguments should be Rational instances”

例如,如果我这样做:

Y  =  np.array([7,1], dtype='int64')  
X  =  Y[0]*3+Y[1]

然后:

a = Fraction(58,X)  

我会得到同样的错误。我还尝试执行 X=X.astype('int')X=X.astype('int32'),但没有成功。

我需要做什么才能将 numpy 数组转换为分数模块所需的“Rational 实例”?

最佳答案

这似乎是 Numpy 整数与 Python 抽象类交互方式的不幸产物之一(它还取决于您运行的是 32 位还是 64 位 Python,因为 dtype='int' 表示 np.int32np.int64,但绝不表示 Python int)。

显式转换为 Python int 应该可行:

Fraction(58, int(X))

关于python - 在 Python 的 Fraction 模块中使用 numpy 向量元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16147559/

相关文章:

c++ - 是否有相当于Python的fractions.Fraction(bignum/任意精度分数/有理数类)?

python - 使用 statsmodel.formula.api 与 statsmodel.api 的 OLS

python - 减去字典中的所有值是值是 float 列表

c++ - 将浮点十进制值转换为分数

python - Python 中的分数

python - Scipy ndimage median_filter 来源

python - __init__ 以函数作为参数(使用 NetworkX)

python - Django 模型属性 - 计算模型多个实例的外键数量

python - 在 Numpy 中交换行会产生一个嵌入式数组

聚合数组的 pythonic 方式(numpy 与否)