Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Minor optimization for Fractions.limit_denominator#93730

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Merged
Merged
Changes from1 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
PrevPrevious commit
NextNext commit
More efficient comparison of candidates
  • Loading branch information
@mdickinson
mdickinson committedJun 12, 2022
commit9ac09a1c7d6e8774a4b0c0233fb638f3c4afd11c
15 changes: 9 additions & 6 deletionsLib/fractions.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -245,14 +245,17 @@ def limit_denominator(self, max_denominator=1000000):
break
p0, q0, p1, q1 = p1, q1, p0+a*p1, q2
n, d = d, n-a*d

k = (max_denominator-q0)//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

# Determine which of the candidate fractions (p0+k*p1)/(q0+k*q1) and
# p1/q1 is closer to self. The distance between the two candidates is
# 1/(q1*(q0+k*q1)), while the distance from p1/q1 to self is
# 1/(q1*(q0+n/d*q1)). So we need to compare q0+k*q1 with 2*(q0+n/d*q1).
# That translates to the following comparison in integers.
if (q0+2*k*q1)*d <= q1*n:
return Fraction(p1, q1, _normalize=False)
else:
returnbound1
returnFraction(p0+k*p1, q0+k*q1, _normalize=False)

@property
def numerator(a):
Expand Down

[8]ページ先頭

©2009-2025 Movatter.jp