Skip to content

Speed up Fraction.__round__ for large negative ndigits #132472

@devdanzin

Description

@devdanzin

Feature or enhancement

Proposal:

Rounding a Fraction to a large negative ndigits takes a long time, only to return Fraction(0, 1):

>>> from fractions import Fraction
>>> large_negative_number = -2**31
>>> d = Fraction(17, 33)
>>> d.__round__(large_negative_number)  # Takes forever, calculating `10**abs(ndigits)`

Using the check below, the code above returns almost instantly:

if ndigits < 0 and int(math.log10(self)) < abs(ndigits):
    return Fraction(0, 1)

I realize there may not be a real use case for this enhancement. OTOH, it's such a simple code change that it might make sense. If it's considered worthy of implementing, I can submit a PR (which also speeds up _round_to_exponent in a similar way).

cc @JelleZijlstra

Has this already been discussed elsewhere?

This is a minor feature, which does not need previous discussion elsewhere

Links to previous discussion of this feature:

It was very briefly discussed on Discord.

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancePerformance or resource usagestdlibStandard Library Python modules in the Lib/ directorytype-featureA feature request or enhancement

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions