Skip to content

Commit f69321c

Browse files
committed
Minor optimization for Fractions.limit_denominator
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.
1 parent 733e15f commit f69321c

File tree

1 file changed

+2
-2
lines changed

1 file changed

+2
-2
lines changed

Lib/fractions.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -247,8 +247,8 @@ def limit_denominator(self, max_denominator=1000000):
247247
n, d = d, n-a*d
248248

249249
k = (max_denominator-q0)//q1
250-
bound1 = Fraction(p0+k*p1, q0+k*q1)
251-
bound2 = Fraction(p1, q1)
250+
bound1 = Fraction(p0+k*p1, q0+k*q1, _normalize=False)
251+
bound2 = Fraction(p1, q1, _normalize=False)
252252
if abs(bound2 - self) <= abs(bound1-self):
253253
return bound2
254254
else:

0 commit comments

Comments
 (0)