Search code examples
pythonpython-3.xlistsympyfractions

How to convert decimal values to fractions in a list of expressions in Python?


import sympy as sp
from fractions import Fraction

M = sp.symbols('M')

diffs = [None, 0, 5*M/2 - 3.5, 0.5 - 3*M/2, -M, M/2 - 1.5, 0, 1.5 - 3*M/2]

#Convert terms of expression to fractions (none of these 2 lines of code work)
diffs = [Fraction(float(val)).limit_denominator() if isinstance(val, float) else val for val in diffs]
#diffs = [sp.Rational(val).limit_denominator() if isinstance(val, float) else val for val in diffs]

print(diffs)

This is the output that I am getting where the terms of the expressions are written as decimals..

[None, 0, 5*M/2 - 3.5, 0.5 - 3*M/2, -M, M/2 - 1.5, 0, 1.5 - 3*M/2]

And this is the correct output that should be shown, indicating the terms as fractions (as long as they can be converted)

[None, 0, 5*M/2 - 5/2, 1/2 - 3*M/2, -M, M/2 - 3/ 2, 0, 3/2 - 3*M/2]

The truth is that I don't want it to print the terms in the results as a function with 2 parameters, for example like this Fraction(2,3) or Rational(2,3), I need for example an output like this 2/3


Solution

  • >>> [nsimplify(i, rational=True) if i else i for i in diffs]
    [None, 0, 5*M/2 - 7/2, 1/2 - 3*M/2, -M, M/2 - 3/2, 0, 3/2 - 3*M/2]