Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
as_integer_ratio() in Python for reduced fraction of a given rational
In this tutorial, we are going to write a program that returns two numbers whose ratio is equal to the given float value. The as_integer_ratio() method helps to achieve our goal by converting a float into its exact fractional representation.
Let's see some examples ?
Input: 1.5 Output: 3 / 2 Input: 5.3 Output: 5967269506265907 / 1125899906842624
Syntax
The as_integer_ratio() method is called on a float value and returns a tuple containing the numerator and denominator ?
float_value.as_integer_ratio()
Return Value
Returns a tuple (numerator, denominator) where both are integers and their ratio equals the original float value. The fraction is always in its simplest form.
Example 1: Simple Decimal
# initializing the float value
float_value = 1.5
# getting integers tuple using the as_integer_ratio() method
integers = float_value.as_integer_ratio()
# printing the integers
print(f'{integers[0]} / {integers[1]}')
3 / 2
Example 2: Complex Decimal
Some decimal numbers cannot be represented exactly in binary floating-point, leading to very large numerators and denominators ?
# initializing the float value
float_value = 5.3
# getting integers tuple using the as_integer_ratio() method
integers = float_value.as_integer_ratio()
# printing the integers
print(f'{integers[0]} / {integers[1]}')
5967269506265907 / 1125899906842624
Example 3: Multiple Values
# testing with multiple float values
values = [0.25, 0.125, 2.75, 0.1]
for val in values:
numerator, denominator = val.as_integer_ratio()
print(f'{val} = {numerator} / {denominator}')
0.25 = 1 / 4 0.125 = 1 / 8 2.75 = 11 / 4 0.1 = 3602879701896397 / 36028797018963968
Key Points
| Aspect | Description |
|---|---|
| Return Type | Tuple of two integers (numerator, denominator) |
| Fraction Form | Always in lowest terms (reduced) |
| Precision | Exact representation of the float's binary value |
Conclusion
The as_integer_ratio() method converts floats to their exact fractional representation as a tuple. Note that some decimals may result in large numbers due to binary floating-point limitations.
