Python Fraction type implements a rational number object.
It keeps both a numerator and a denominator explicitly.
Fraction resides in a module.
You can import its constructor and pass in a numerator and a denominator to make one.
from fractions import Fraction x = Fraction(1, 3) # Numerator, denominator y = Fraction(4, 6) # Simplified to 2, 3 by gcd # w w w . ja v a2s. c o m print( x ) print( y )
Once created, Fractions can be used in mathematical expressions as usual:
from fractions import Fraction x = Fraction(1, 3) # Numerator, denominator y = Fraction(4, 6) # Simplified to 2, 3 by gcd # from ww w. j av a 2 s . co m print( x ) print( y ) print( x + y ) print( x - y ) # Results are exact: numerator, denominator print( x * y )
Fraction objects can be created from floating-point number strings, much like decimals:
from fractions import Fraction x = Fraction(1, 3) # Numerator, denominator y = Fraction(4, 6) # Simplified to 2, 3 by gcd print( Fraction('.25') ) print( Fraction('1.25') ) print( Fraction('.25') + Fraction('1.25') )