Skip to content
Closed
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Fix boundary case.
  • Loading branch information
mscuthbert committed Jun 4, 2022
commit a1a4fc863d58dbcd25f0b2aab4de162ce2967064
4 changes: 2 additions & 2 deletions Lib/fractions.py
Original file line number Diff line number Diff line change
Expand Up @@ -234,7 +234,7 @@ def limit_denominator(self, max_denominator=1000000):
if max_denominator < 1:
raise ValueError("max_denominator should be at least 1")
if self._denominator <= max_denominator:
return Fraction(self._numerator, self._denominator)
return Fraction(self._numerator, self._denominator, _normalize=False)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does this change make a significant difference to performance? If not, I'd suggest reverting it, both for readability and for the purposes of keeping the PR focused. From looking at the code, a simple Fraction(self) shouldn't end up doing any gcd calculation here.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It actually saves 30% on this case based on tests above -- however, I hadn't realized at the time that the return self was executed in this branch and no normalization was done. The speed increase is probably based on the isinstance() check, which just keeps getting faster and faster in subsequent versions, so it might eventually be the faster route. I've removed the change.

If Fractions are eventually to be truly immutable and hashable, then return self is the correct response here, but that is probably backwards incompatible with real code where people change _numerator or _denominator after instantiation.


p0, q0, p1, q1 = 0, 1, 1, 0
n, d = self._numerator, self._denominator
Expand All @@ -261,7 +261,7 @@ def limit_denominator(self, max_denominator=1000000):

difference = ((bound1_minus_self_n * bound2_minus_self_d)
- (bound2_minus_self_n * bound1_minus_self_d))
if difference > 0:
if difference >= 0:
return Fraction(bound2_n, bound2_d)
else:
return Fraction(bound1_n, bound1_d)
Expand Down