Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Minor optimization for Fractions.limit_denominator #93730

Merged

Conversation

mdickinson
Copy link
Member

@mdickinson mdickinson commented Jun 11, 2022

When we construct the upper and lower candidates in limit_denominator, the numerator and denominator are already relatively prime (and the denominator positive) by construction, so there's no need to go through the usual normalisation in the constructor. This saves a couple of potentially expensive gcd calls.

We also replace the comparison used to determine which bound to pick with a simpler and faster version.

Inspired by Michael Scott Asato Cuthbert in GH-93477.

When we construct the upper and lower candidates in limit_denominator,
the numerator and denominator are already relatively prime (and the
denominator positive) by construction, so there's no need to go through
the usual normalisation in the constructor. This saves a couple of
potentially expensive gcd calls.

Suggested by Michael Scott Asato Cuthbert in pythonGH-93477.
Lib/fractions.py Outdated
bound1 = Fraction(p0+k*p1, q0+k*q1)
bound2 = Fraction(p1, q1)
bound1 = Fraction(p0+k*p1, q0+k*q1, _normalize=False)
bound2 = Fraction(p1, q1, _normalize=False)
if abs(bound2 - self) <= abs(bound1-self):
Copy link
Contributor

@rhettinger rhettinger Jun 11, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While you're here, can you fix-up the spacing around the operator on line 252?

@mdickinson mdickinson marked this pull request as ready for review Jun 12, 2022
@mdickinson
Copy link
Member Author

@mdickinson mdickinson commented Jun 12, 2022

Now ready for review.

@mscuthbert: If you have a moment, please could you take a look at this and let me know whether it meets your needs?

@ambv ambv merged commit 420f0df into python:main Jun 21, 2022
12 checks passed
@mscuthbert
Copy link

@mscuthbert mscuthbert commented Jun 22, 2022

Thank you @mdickinson a ton!

@mdickinson mdickinson deleted the fractions-limit-denominator-optimizations branch Jun 23, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
performance skip issue skip news
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

5 participants