Python - Numeric Fraction conversions

Introduction

To support fraction conversions, floating-point objects have a method that yields their numerator and denominator ratio.

Fractions have a from_float method, and float accepts a Fraction as an argument.

The * in the second test is special syntax that expands a tuple into individual arguments.

Demo

from fractions import Fraction 

print( (2.5).as_integer_ratio() )   # float object method 
# w  w  w. j  ava  2  s .c o m
f = 2.5 
z = Fraction(*f.as_integer_ratio()) # Convert float -> fraction: two args 
print( z )                          # Same as Fraction(5, 2) 

x = Fraction(1, 3)                  # Numerator, denominator 
print( x )                          # x from prior interaction 
print( x + z )                      # 5/2 + 1/3 = 15/6 + 2/6 
print( float(x) )                   # Convert fraction -> float 
print( float(z) )
print( float(x + z) )
print( 17 / 6 )

print( Fraction.from_float(1.75) )  # Convert float -> fraction: other way 
print( Fraction(*(1.75).as_integer_ratio()) )

Result

Related Topic