这是 SymPy 文档中gochas and pitfalls 之一的示例。我的回答基本上会重申那里所说的话。我强烈建议您通过它。
当您键入1/7 时,Python 解释器会在 SymPy 有机会将其识别为有理数之前将其更改为浮点数。为了让 SymPy 在 Python 之前对其进行评估,您需要使用其他方法。您已经使用M2 展示了其他方法之一:将 SymPy 对象除以 7 而不是 Python int 除以 7。以下是其他几种方法:
from sympy import *
M = Matrix([[Rational(1, 7),Rational(2, 7)],[Rational(3, 7),Rational(4, 7)]]) # create a Rational object
print(det(M))
M = Matrix([[S(1)/7,S(2)/7],[S(3)/7,S(4)/7]]) # divide a SymPy Integer by 7
print(det(M))
M = Matrix([[S("1/7"),S("2/7")],[S("3/7"),S("4/7")]]) # let SymPy interpret it
print(det(M))
M = Matrix([[1,2],[3,4]])/7 # divide a SymPy Matrix by 7
print(det(M))
M = S("Matrix([[1/7,2/7],[3/7,4/7]])") # throw the whole thing into SymPy
print(det(M))
以上所有将给出合理的决定因素。可能还有更多方法可以让 SymPy 识别有理数。