+

as_integer_ratio () in Python for a reduced fraction of a given rational

Examples :

 Input: d = 2.5 Output: 5/2 Explanation: 5/2 gives 2.5 which is the reduced form of any fraction that gives 2.5 Input: d = 1.5 Output: 3/2 

Python as_integer_ratio () Function:
Returns a pair of integers whose ratio is exactly equal to the original floating point value and has a positive denominator.

Syntax:
float. as_integer_ratio ()
Return Value:
Tupple (a pair of integers)
Errors:
Raises OverflowError on infinities and a ValueError on NaNs.

In Python, we have a built-in function as_integer_ratio (), that prints the reduced fractional form of any given rational number d. We need to store this in any variable and then print the 0th index and 1st index of the stored fraction.

# function to display fraction
# given rational number

def reducedfraction ( d):

 

# a function that converts a rational number

# to a reduced fraction

b = d.as_integer_ratio ()

 

  # reduced the list containing the fraction  

return

 
# driver code

b = reducedfraction ( 2.5 )

print b [ 0 ], "/" , b [ 1

Exit :

 5/2 
Get Solution for free from DataCamp guru