= Python Fractions = '''`fractions`''' is a module supporting arithmetic with rational numbers. <> ---- == Usage == === Fraction === A `Fraction` can be instantiated from integers, floats, strings, and [[Python/Decimal|Decimal objects]]. {{{ import fractions fractions.Fraction(-8, 5) #Fraction(-8, 5) # The numerator-denominator pair can be given as separate arguments or as a formatted string fractions.Fraction('-8/5') #Fraction(-8, 5) # Fraction reduces and moves signs to the numerator automatically fractions.Fraction(16, -10) #Fraction(-8, 5) # Note the defaults fractions.Fraction(123) #Fraction(123, 1) fractions.Fraction() #Fraction(0, 1) }}} The components can be access with the `numerator` and `denominator` properties, or the `as_integer_ratio` method. ---- === Limit_Denominator === To approximate a fraction, use the `limit_denominator` method. It takes an integer argument that is used to construct a new `Fraction` with a denominator ''no larger'' than that integer. {{{ import fractions fractions.Fraction('3.1415926535897932').limit_denominator(1000) #Fraction(355, 113) }}} ---- == See also == [[https://docs.python.org/3/library/fractions.html|Python fractions module documentation]] [[https://pymotw.com/3/fractions/|Python Module of the Day article for fractions]] ---- CategoryRicottone