Write a Python program to convert a float to ratio


The program is converting a decimal number to a fraction using the Fraction function from the fractions module in Python. First, the program initializes a floating-point number val to 9.2.

Next, the program calls the Fraction function and passes in val as an argument. This creates a Fraction object with a numerator and denominator that approximate the value of val.

Finally, the program calls the limit_denominator method on the Fraction object. This returns a new Fraction object that has the closest approximation of the original fraction, but with a denominator no larger than a certain limit. By default, the limit is set to 1,000,000, but it can be changed by passing a different value as an argument to the limit_denominator method.

The program then prints out the result of this method call, which is the fraction that is closest to the original decimal value of 9.2 with a denominator of at most 1,000,000

Source Code

from fractions import Fraction
val = 9.2
print(Fraction(val).limit_denominator())

Output

46/5

Example Programs