Search code examples
pythonfractions

Can I get a fraction from a number in python?


I am doing some calculations and before outputting I want to change the number to a fraction. For example 0.25 would become 1/4, well in a list of the two numbers [1, 4].


Solution

  • Use the fractions module to do that:

    >>> import fractions
    >>> fractions.Fraction(0.25)
    Fraction(1, 4)
    >>> f = fractions.Fraction(0.25)
    >>> f.numerator
    1
    >>> f.denominator
    4
    

    For arbitrary floats as input, you really want to use the .limit_denominator() method to limit your fractions to sane approximations of the floating point number:

    >>> from math import pi, cos
    >>> fractions.Fraction(cos(pi/3))
    Fraction(4503599627370497, 9007199254740992)
    >>> fractions.Fraction(cos(pi/3)).limit_denominator()
    Fraction(1, 2)