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

gh-72902: speedup Fraction.from_decimal/float in typical cases#133251

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

Open
skirpichev wants to merge2 commits intopython:main
base:main
Choose a base branch
Loading
fromskirpichev:opt-Fraction.from_Decimal/72902
Open
Show file tree
Hide file tree
Changes fromall commits
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
20 changes: 10 additions & 10 deletionsLib/fractions.py
View file
Open in desktop
Original file line numberDiff line numberDiff line change
Expand Up@@ -335,23 +335,23 @@ def from_float(cls, f):
Beware that Fraction.from_float(0.3) != Fraction(3, 10).

"""
if isinstance(f, numbers.Integral):
if not isinstance(f, float):
if not isinstance(f, numbers.Integral):
raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
(cls.__name__, f, type(f).__name__))
return cls(f)
elif not isinstance(f, float):
raise TypeError("%s.from_float() only takes floats, not %r (%s)" %
(cls.__name__, f, type(f).__name__))
return cls._from_coprime_ints(*f.as_integer_ratio())

@classmethod
def from_decimal(cls, dec):
"""Converts a finite Decimal instance to a rational number, exactly."""
from decimal import Decimal
if isinstance(dec,numbers.Integral):
dec = Decimal(int(dec))
elif not isinstance(dec, Decimal):
raise TypeError(
"%s.from_decimal() only takes Decimals, not %r (%s)" %
(cls.__name__,dec, type(dec).__name__))
ifnotisinstance(dec,Decimal):
if not isinstance(dec, numbers.Integral):
raise TypeError(
"%s.from_decimal() only takes Decimals, not %r (%s)" %
(cls.__name__, dec, type(dec).__name__))
dec = int(dec)
return cls._from_coprime_ints(*dec.as_integer_ratio())

@classmethod
Expand Down
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
Optimize (~x1.40-50 speedup) :meth:`fractions.Fraction.from_decimal` and
:meth:`fractions.Fraction.from_float` for :class:`~decimal.Decimal` and
:class:`float` inputs, respectively. Patch by Sergey B Kirpichev.
Loading

[8]ページ先頭

©2009-2025 Movatter.jp