numpy中分数的线性系统解决方案

Linear system solution with fractions in numpy

我有矩阵 A 和右侧向量 yfractions.Fraction 个对象表示:

import random, fractions, numpy as np

A = np.zeros((3, 3), dtype=fractions.Fraction)
y = np.zeros((3, 1), dtype=fractions.Fraction)
for i in range(3):
    for j in range(3):
        A[i, j] = fractions.Fraction(np.random.randint(0, 4), np.random.randint(1, 6))
    y[i] = fractions.Fraction(np.random.randint(0, 4), np.random.randint(1, 6))

我想使用 numpy 中提供的函数求解系统 A*x = y 并得到以分数对象表示的结果,但不幸的是基本 x = np.linalg.solve(A, y) returns标准浮点值的结果:

>>> np.linalg.solve(A, y)

array([[-1.5245283 ],
       [ 2.36603774],
       [ 0.56352201]])

有没有办法用分数对象得到准确的结果?


编辑

我想做的事情对于 numpy 的内置功能来说是不可行的(从 1.10 版开始 - 请参阅 Mad Physicist 的回答)。可以做的是实现 his/her 自己的基于高斯消元法的线性求解器,它依赖于求和、减法、乘法和除法,所有这些都是明确定义的,并且完全使用分数对象执行(只要分子和分母适合数据类型,我认为是任意长)。

如果您真的对此感兴趣,只需自己实现一个求解器,即可轻松快速地完成(遵循众多在线教程之一)。我不太感兴趣,所以我会坚持使用浮点数结果。

根据 this thread on the python mailing list. The response suggests that you can use sympy for matrices of rationals up to size 4x4. If you are tied to numpy for some reason, you can consider taking and using the inverse of a 3x3 matrix "manually". Step by step tutorials on how to do this can be found on http://www.mathsisfun.com/algebra/matrix-inverse-minors-cofactors-adjugate.html 以及大量其他关于矩阵求逆的教程,使用纯 numpy 求逆有理数矩阵似乎是不可能的。

恕我直言,没有希望了。在许多情况下都有效的解决方案:

y = np.zeros(3, dtype=fractions.Fraction)
....
X= np.linalg.solve(A,y)
s=[fractions.Fraction.from_float(x).limit_denominator(6**9) for x in X]
print(s,y==dot(A,s))

利用属性解几乎是一个分子分母都很少的分数,求出来。