From f69321c69ba16f49da45bd78ea4fd0b4b8a9df27 Mon Sep 17 00:00:00 2001 From: Mark Dickinson Date: Sat, 11 Jun 2022 17:35:14 +0100 Subject: [PATCH] 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 GH-93477. --- Lib/fractions.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Lib/fractions.py b/Lib/fractions.py index f9ac882ec002fa..7b533bf98cbd9b 100644 --- a/Lib/fractions.py +++ b/Lib/fractions.py @@ -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: