Search code examples
pythonfloating-pointfractions

How to convert a special float into a fraction object


I have this function inside another function:

def _sum(k):
        return sum([(-1) ** v * fractions.Fraction(str(bin_coeff(k, v))) * fractions.Fraction((n + v) ** m, k + 1) for v in xrange(k + 1)])

When i call fractions.Fraction on bin_coeff it reports me this error:

ValueError: Invalid literal for Fraction: '1.05204948186e+12'

How can can I convert a float in that form into a Fraction object?

Is there a better solution than:

fractions.Fraction(*bin_coeff(k, v).as_integer_ratio())

Thank you,
rubik

P.S. bin_coeff always returns a float


Solution

  • I cannot reproduce your error in py3k, but you could pass your float straight to from_float class method:

    >>> fractions.Fraction.from_float(1.05204948186e+12)
    Fraction(1052049481860, 1)