Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sympy.Rational doesn't work correctly with fractions like 1/3

I have this code:

import sympy as smp
a = smp.Rational(1/3)
print('1/3: ', a)
a = smp.Rational(1/6)
print('1/6: ', a)
a = smp.Rational(1/2)
print('1/2: ', a)
a = smp.Rational(1/4)
print('1/4: ', a)

and this result:

1/3:  6004799503160661/18014398509481984
1/6:  6004799503160661/36028797018963968
1/2:  1/2
1/4:  1/4

sympy doesn’t work correctly with different fractions like 1/3, 1/5, 1/6, etс.
How can i solve this problem?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

There is an example

>Solution :

When you write 1/3, that immediately performs the division. So

sympy.Rational(1/3)

is the same as

sympy.Rational(6004799503160661/18014398509481984)

because in Python,

1/3 == 6004799503160661/18014398509481984

You must pass the numerator and denominator to the Rational factory:

sympy.Rational(1, 3)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading