What is Fractions.as_integer_ratio() in Python?

Overview

The as_integer_ratio method of the Fractions class is used to obtain the numerator and a positive denominator for a given value such that the ratio value of the obtained numerator and denominator is the same as the given value. The method returns a tuple of two elements where the element at the index 0 is the numerator and the element at index 1 is the denominator.

This method can also be used directly on integers and floating-point numbers.

This method was introduced in Python version 3.8.

Syntax

as_integer_ratio()

Parameters

This method has no parameters.

Return value

This method returns a tuple of two integers, whose ratio is equal to the Fraction object and with a positive denominator.

import fractions
fraction_1 = fractions.Fraction(2.1)
print("Integer ratio of 2.1 is ", fraction_1.as_integer_ratio())
floating_number = 5.422
print("Integer ratio of 5.422 is ", floating_number.as_integer_ratio())
integer_number = 5
print("Integer ratio of 5 is ", integer_number.as_integer_ratio())

Explanation

  • Line 1: We import the fractions module.
  • Line 3: We create an instance of the Fraction class called fraction_1 with the value 2.1.
  • Line 5: We print the value returned by invoking the as_integer_ratio() method on fraction_1.
  • Line 7: We define a floating-point value called floating_number.
  • Line 9: We print the value returned by invoking the as_integer_ratio() method on floating_number object.
  • Line 11: We define an integer value called integer_number.
  • Line 13: We print the value returned by invoking the as_integer_ratio() method on integer_number object.

Free Resources