Python - Numeric Fraction Type

Introduction

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.

Demo

from fractions import Fraction 
x = Fraction(1, 3)                    # Numerator, denominator 
y = Fraction(4, 6)                    # Simplified to 2, 3 by gcd 
# from  ww  w.  j a  va 2  s.c  o  m
print( x )
print( y )

Result

Once created, Fractions can be used in mathematical expressions as usual:

Demo

from fractions import Fraction 
x = Fraction(1, 3)                    # Numerator, denominator 
y = Fraction(4, 6)                    # Simplified to 2, 3 by gcd 
#   ww w . j  av a  2s  . c  o  m
print( x )
print( y )
print( x + y )
print( x - y )                           # Results are exact: numerator, denominator 
print( x * y )

Result

Fraction objects can be created from floating-point number strings, much like decimals:

Demo

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') )

Result

Related Topics