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. We have a method called as_integer_ratio() that helps to achieve our goal.

Let's see some examples.

Input:
1.5
Output:
3 / 2
Input:
5.3
Output:
5967269506265907 / 1125899906842624

Let's examine the code.

Example

# 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]}')

Output

If you run the above code, you will get the following results.

3 / 2

Let's see another example.

Example

# 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]}')

Output

If you run the above code, you will get the following results.

5967269506265907 / 1125899906842624

Conclusion

If you have any queries in the tutorial, ask them in the comment section.

raja
Published on 01-Nov-2019 09:42:09
Advertisements