Rational numbers in python

Rational numbers are fractions of ineger

Neeraj Dana
Neeraj Dana

Rational numbers are fractions of ineger

1/3
22/7
55/5

In python rational numbers are represented by Fraction Class from fractions module some examples of fraction would be

from fractions import Fraction

val = Fraction(3,4)
value = Fraction(35,15)
negativevalue = Fraction(-35,15)

Fraction Constructor

in python ther are certain ways of creating a fraction they are

 Fraction(numerator,denominator)
 Fraction(numerator=0,denominator=1)
 Fraction(decimal)
 Fraction(float)
 Fraction(string)   

so in the above code the default values of the numerator  is 0 and denominator is 1

x = Fraction('12')
// it will be converted into 
// x = Fraction(12,1)

Operators on Fraction

all the basic operations on fractions is application such as add subtract multiply and divide and others

1/2 + 1/4 = 3/4

Fraction(1,2) + Fraction(1,4) = Fraction(3,4)

print (Fraction(18, 5) / Fraction(18, 10)) 
# returns Fraction(2, 1) 
   
print (Fraction(18, 5) * Fraction(16, 19)) 
# returns Fraction(288, 95) 
   
print (Fraction(18, 5) * Fraction(15, 36)) 
# returns Fraction(3, 2) 
   
print (Fraction(12, 5) ** Fraction(12, 10)) 
# returns 2.8592589556010197
Python