You can use Fraction.from_float
:
>>> from fractions import Fraction
>>> Fraction.from_float(0.5)
Fraction(1, 2)
Even though it seems less smart than Mathematica:
>>> Fraction.from_float(3.33333333)
Fraction(7505999371444827, 2251799813685248)
It actually simply convert the float to its exact rational representation(so numbers that cannot be written exactly as floats wont be converted "correctly").
You can get more "human-readable" limiting the denominator:
>>> Fraction.from_float(3.333333333).limit_denominator(10)
Fraction(10, 3)
Even though it is trickier to understand which limit you should put to get the "correct" fraction, and it may happen that it is still impossible to obtain it due to the float representation.
If you have to stay with sympy
than I don't think you can avoid using nsimplify
,
which seems written exactly for such purposes.
edit: from python2.7+ you can simply call Fraction(0.5)
instead of using the from_float
method.
sympy.simplify.nsimplify()
callssympy.simplify._real_to_rational()
if the rational flag is true, but does not pass any tolerance parameters. Perhaps I will play around with this to get what I want. Thank you! – Barabarabarabas