What is the Fractions.limit_denominator() method in Python?
Overview
The limit_denominator method of the Fractions class is used to restrict the denominator value to a value that is less than or equal to the specified value for the given Fraction object. We use this method to find the rational approximations for floating-point numbers.
The method returns a new Fraction object with the maximum value of the denominator as the specified value.
Syntax
limit_denominator(max_denominator=1000000)
Parameters
max_denominator: The maximum value of the denominator.
Return value
A new Fraction object.
Example
import fractionsfloat_value = -5.422fraction_object = fractions.Fraction.from_float(float_value)new_fraction_object = fraction_object.limit_denominator(max_denominator=1432)print("Fraction without limit_denominator(1432) for %f - %s" % (float_value, fraction_object))print("Fraction with limit_denominator(1432) for %f - %s" % (float_value, new_fraction_object))
Explanation
- Line 1: We import the
fractionsmodule. - Line 3: A floating-point value called
float_valueis defined. - Line 5: An instance of
Fractionclass is obtained fromfloat_valueusing thefrom_float()method.
Note: Read more about the
from_float()method here.
- Line 7: A new
Fractionobject callednew_fraction_objectis obtained where we restrict the maximum value of the denominator to1432. - Lines 9–10: We print the
new_fraction_objectandfraction_object.
In the output, we can infer that the denominator of new_fraction_object is less than 1432.