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 fractions
float_value = -5.422
fraction_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 fractions module.
  • Line 3: A floating-point value called float_value is defined.
  • Line 5: An instance of Fraction class is obtained from float_value using the from_float() method.

Note: Read more about the from_float() method here.

  • Line 7: A new Fraction object called new_fraction_object is obtained where we restrict the maximum value of the denominator to 1432.
  • Lines 9–10: We print the new_fraction_object and fraction_object.

In the output, we can infer that the denominator of new_fraction_object is less than 1432.

Free Resources