Skip to content

Commit

Permalink
Minor optimization for Fractions.limit_denominator
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
mdickinson committed Jun 11, 2022
1 parent 733e15f commit f69321c
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Lib/fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -247,8 +247,8 @@ def limit_denominator(self, max_denominator=1000000):
n, d = d, n-a*d

k = (max_denominator-q0)//q1
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):
return bound2
else:
Expand Down

0 comments on commit f69321c

Please sign in to comment.