Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is python's fractions.limit_denominator implemented?

limit_denominator(max_denominator=1000000)
Finds and returns the closest Fraction to self that has denominator at most max_denominator. This method is useful for finding rational approximations to a given floating-point number:

>>>
>>> from fractions import Fraction
>>> Fraction('3.1415926535897932').limit_denominator(1000)
Fraction(355, 113)

It shouldn't be something like trying a/999, b/998, c/997.. and find best approximations.

like image 411
thkang Avatar asked Nov 18 '12 04:11

thkang


People also ask

How are fractions represented in Python?

class fractions. Fraction(string) : This requires the string or unicode instance and a fraction instance with same value is returned. Form for this instance : [sign] numerator ['/' denominator] Here, sign represents '+' or '-' and numerator and denominator are strings of single digits.

Can Python handle fractions?

From Python 3.2 onwards, you can also construct a Fraction instance directly from a decimal. Decimal instance.

How do you simplify fractions in Python?

Step 1: Write the factors of numerator and denominator. Step 2: Determine the highest common factor of numerator and denominator. Step 3: Divide the numerator and denominator by their highest common factor (HCF). The fraction so obtained is in the simplest form.


1 Answers

The fractions module is written in Python and you can just look at the source code. It contains the following comment.

    # Algorithm notes: For any real number x, define a *best upper
    # approximation* to x to be a rational number p/q such that:
    #
    #   (1) p/q >= x, and
    #   (2) if p/q > r/s >= x then s > q, for any rational r/s.
    #
    # Define *best lower approximation* similarly.  Then it can be
    # proved that a rational number is a best upper or lower
    # approximation to x if, and only if, it is a convergent or
    # semiconvergent of the (unique shortest) continued fraction
    # associated to x.
    #
    # To find a best rational approximation with denominator <= M,
    # we find the best upper and lower approximations with
    # denominator <= M and take whichever of these is closer to x.
    # In the event of a tie, the bound with smaller denominator is
    # chosen.  If both denominators are equal (which can happen
    # only when max_denominator == 1 and self is midway between
    # two integers) the lower bound---i.e., the floor of self, is
    # taken.
like image 127
kindall Avatar answered Oct 16 '22 14:10

kindall