Thanks to visit codestin.com
Credit goes to github.com

Skip to content

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 our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all 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 deletions Lib/fractions.py
Original file line number Diff line number Diff 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__))
if not isinstance(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
Original file line number Diff line number Diff 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