Python - Fraction and mixed types

Introduction

Some type mixing is allowed in expressions, though Fraction must sometimes be manually propagated to retain accuracy.

Demo

from fractions import Fraction 
x = Fraction(1, 3)                    # Numerator, denominator 
print( x )
print( x + 2 )                                  # Fraction + int -> Fraction 
print( x + 2.0 )                                # Fraction + float -> float 
print( x + (1./3) )                             # Fraction + float -> float 
print( x + (4./3) )
print( x + Fraction(4, 3) )                     # Fraction + Fraction -> Fraction
#   www  .  ja  v  a  2  s .  c om

Result

Although you can convert from floating point to fraction, in some cases there is an unavoidable precision loss when you do so.

When needed, you can simplify such results by limiting the maximum denominator value:

Demo

from fractions import Fraction 
print( 4.0 / 3 )# from   www.ja  va 2  s. c  o m
print( (4.0 / 3).as_integer_ratio() ) # Precision loss from float 

x = Fraction(1, 3)                    # Numerator, denominator 

print( x )
a = x + Fraction(*(4.0 / 3).as_integer_ratio()) 
print( a )
print( 22123123136852479 / 13510712312312388 )      # 5 / 3 (or close to it!) 
print( a.limit_denominator(10) )      # Simplify to closest fraction

Result

Related Topic