Skip to content

Commit 9095233

Browse files
committed
Apply optimisation from python/cpython#93730
1 parent df8b641 commit 9095233

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/quicktions.pyx

+8-5
Original file line numberDiff line numberDiff line change
@@ -569,12 +569,15 @@ cdef class Fraction:
569569
n, d = d, n-a*d
570570

571571
k = (max_denominator-q0)//q1
572-
bound1 = Fraction(p0+k*p1, q0+k*q1)
573-
bound2 = Fraction(p1, q1)
574-
if abs(bound2 - self) <= abs(bound1-self):
575-
return bound2
572+
573+
# Determine which of the candidates (p0+k*p1)/(q0+k*q1) and p1/q1 is
574+
# closer to self. The distance between them is 1/(q1*(q0+k*q1)), while
575+
# the distance from p1/q1 to self is d/(q1*self._denominator). So we
576+
# need to compare 2*(q0+k*q1) with self._denominator/d.
577+
if 2*d*(q0+k*q1) <= self._denominator:
578+
return Fraction(p1, q1, _normalize=False)
576579
else:
577-
return bound1
580+
return Fraction(p0+k*p1, q0+k*q1, _normalize=False)
578581

579582
@property
580583
def numerator(self):

0 commit comments

Comments
 (0)