Marc Bogaerts
Marc Bogaerts

Reputation: 172

How to obtain only rational and not floating point results using sympy

I consider following matrices:

M1 = Matrix([[1/7,2/7],[3/7,4/7]])
M2 = Matrix([[1,2],[3,4]])/7

which are evidently identical, but when I determine their determinant I obtain different results:

print(M1.det())
print(M2.det())

giving the following results:

-0.0408163265306122
-2/49

I would like the first result to be expressed as a rational and not as a floating point.

Upvotes: 2

Views: 690

Answers (1)

Chris du Plessis
Chris du Plessis

Reputation: 1370

This is an example of one of the gochas and pitfalls from SymPy's documentation. My answer will basically reiterate what is said there. I highly recommend going through it.

When you type 1/7, the Python interpreter changes it into a float before SymPy has a chance to identify it as a rational number. In order for SymPy to evaluate it before Python does, you need to use some other method. You have already shown one of those other methods with M2: divide a SymPy object by 7 instead of a Python int by 7. Here are a few other ways:

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))

All of the above will give rational determinants. There are probably many more ways to make SymPy identify a rational number.

Upvotes: 4

Related Questions