Skip to content

Commit

Permalink
Apply optimisation from python/cpython#93730
Browse files Browse the repository at this point in the history
  • Loading branch information
scoder committed Jan 25, 2023
1 parent df8b641 commit 9095233
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions src/quicktions.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -569,12 +569,15 @@ cdef class Fraction:
n, d = d, n-a*d

k = (max_denominator-q0)//q1
bound1 = Fraction(p0+k*p1, q0+k*q1)
bound2 = Fraction(p1, q1)
if abs(bound2 - self) <= abs(bound1-self):
return bound2

# Determine which of the candidates (p0+k*p1)/(q0+k*q1) and p1/q1 is
# closer to self. The distance between them is 1/(q1*(q0+k*q1)), while
# the distance from p1/q1 to self is d/(q1*self._denominator). So we
# need to compare 2*(q0+k*q1) with self._denominator/d.
if 2*d*(q0+k*q1) <= self._denominator:
return Fraction(p1, q1, _normalize=False)
else:
return bound1
return Fraction(p0+k*p1, q0+k*q1, _normalize=False)

@property
def numerator(self):
Expand Down

0 comments on commit 9095233

Please sign in to comment.