summaryrefslogtreecommitdiffstats
path: root/Lib/fractions.py
Commit message (Collapse)AuthorAgeFilesLines
* gh-121797: Add class method Fraction.from_number() (GH-121800)Serhiy Storchaka2024-10-141-1/+24
| | | | | | | | It is an alternative constructor which only accepts a single numeric argument. Unlike to Fraction.from_float() and Fraction.from_decimal() it accepts any real numbers supported by the standard constructor (int, float, Decimal, Rational numbers, objects with as_integer_ratio()). Unlike to the standard constructor, it does not accept strings.
* gh-82017: Support as_integer_ratio() in the Fraction constructor (GH-120271)Serhiy Storchaka2024-07-191-4/+4
| | | | | Any objects that have the as_integer_ratio() method (e.g. numpy.float128) can now be converted to a fraction.
* gh-119838: Treat Fraction as a real value in mixed arithmetic operations ↵Serhiy Storchaka2024-06-031-2/+2
| | | | with complex (GH-119839)
* gh-119189: Fix the power operator for Fraction (GH-119242)Joshua Herman2024-05-311-1/+3
| | | | | | When using the ** operator or pow() with Fraction as the base and an exponent that is not rational, a float, or a complex, the fraction is no longer converted to a float.
* gh-119594: Improve pow(fraction.Fraction(), b, modulo) error message (#119593)Wim Jeantine-Glenn2024-05-291-1/+3
| | | | | | If one calls pow(fractions.Fraction, x, module) with modulo not None, the error message now says that the types are incompatible rather than saying pow only takes 2 arguments. Implemented by having fractions.Fraction __pow__ accept optional modulo argument and return NotImplemented if not None. pow() then raises with appropriate message. --------- Co-authored-by: Mark Dickinson <dickinsm@gmail.com>
* gh-102840: Fix confused traceback when floordiv or mod operations happens ↵Kirill Podoprigora2024-02-101-6/+7
| | | | between Fraction and complex objects (GH-102842)
* gh-114014: Update `fractions.Fraction()`'s rational parsing regex (#114015)Crowthebird2024-01-131-10/+10
| | | | | | | | Fix a bug in the regex used for parsing a string input to the `fractions.Fraction` constructor. That bug led to an inconsistent exception message being given for some inputs. --------- Co-authored-by: blurb-it[bot] <43283697+blurb-it[bot]@users.noreply.github.com> Co-authored-by: Mark Dickinson <dickinsm@gmail.com>
* gh-67790: Support basic formatting for Fraction (#111320)Mark Dickinson2023-12-161-19/+68
| | | | | | | | | | | PR #100161 added fancy float-style formatting for the Fraction type, but left us in a state where basic formatting for fractions (alignment, fill, minimum width, thousands separators) still wasn't supported. This PR adds that support. --------- Co-authored-by: Serhiy Storchaka <storchaka@gmail.com>
* gh-101825: Clarify that as_integer_ratio() output is always normalized (#101843)Sergey B Kirpichev2023-02-271-3/+2
| | | | | | | | | Make docstrings for `as_integer_ratio` consistent across types, and document that the returned pair is always normalized (coprime integers, with positive denominator). --------- Co-authored-by: Owain Davies <116417456+OTheDev@users.noreply.github.com> Co-authored-by: Mark Dickinson <dickinsm@gmail.com>
* gh-101773: Optimize creation of Fractions in private methods (#101780)Sergey B Kirpichev2023-02-271-33/+46
| | | | | | This PR adds a private `Fraction._from_coprime_ints` classmethod for internal creations of `Fraction` objects, replacing the use of `_normalize=False` in the existing constructor. This speeds up creation of `Fraction` objects arising from calculations. The `_normalize` argument to the `Fraction` constructor has been removed. Co-authored-by: Pieter Eendebak <pieter.eendebak@gmail.com> Co-authored-by: Mark Dickinson <dickinsm@gmail.com>
* gh-67790: Support float-style formatting for Fraction instances (#100161)Mark Dickinson2023-01-221-0/+206
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | | This PR adds support for float-style formatting for `Fraction` objects: it supports the `"e"`, `"E"`, `"f"`, `"F"`, `"g"`, `"G"` and `"%"` presentation types, and all the various bells and whistles of the formatting mini-language for those presentation types. The behaviour almost exactly matches that of `float`, but the implementation works with the exact `Fraction` value and does not do an intermediate conversion to `float`, and so avoids loss of precision or issues with numbers that are outside the dynamic range of the `float` type. Note that the `"n"` presentation type is _not_ supported. That support could be added later if people have a need for it. There's one corner-case where the behaviour differs from that of float: for the `float` type, if explicit alignment is specified with a fill character of `'0'` and alignment type `'='`, then thousands separators (if specified) are inserted into the padding string: ```python >>> format(3.14, '0=11,.2f') '0,000,003.14' ``` The exact same effect can be achieved by using the `'0'` flag: ```python >>> format(3.14, '011,.2f') '0,000,003.14' ``` For `Fraction`, only the `'0'` flag has the above behaviour with respect to thousands separators: there's no special-casing of the particular `'0='` fill-character/alignment combination. Instead, we treat the fill character `'0'` just like any other: ```python >>> format(Fraction('3.14'), '0=11,.2f') '00000003.14' >>> format(Fraction('3.14'), '011,.2f') '0,000,003.14' ``` The `Fraction` formatter is also stricter about combining these two things: it's not permitted to use both the `'0'` flag _and_ explicit alignment, on the basis that we should refuse the temptation to guess in the face of ambiguity. `float` is less picky: ```python >>> format(3.14, '0<011,.2f') '3.140000000' >>> format(Fraction('3.14'), '0<011,.2f') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/mdickinson/Repositories/python/cpython/Lib/fractions.py", line 414, in __format__ raise ValueError( ValueError: Invalid format specifier '0<011,.2f' for object of type 'Fraction'; can't use explicit alignment when zero-padding ```
* gh-91851: Micro optimizations for arithmetic between Fractions (#25518)Sergey B Kirpichev2023-01-081-10/+12
| | | | | | | | Adapted from https://github.com/python/cpython/pull/24779/commits/046c84e8f9 This makes arithmetic between Fractions with small components just as fast as before python/cpython#24779, at some expense of mixed arithmetic (e.g. Fraction + int).
* gh-91851: Trivial optimizations in Fraction (#100791)Sergey B Kirpichev2023-01-061-5/+6
| | | | | | | Make some trivial performance optimizations in Fraction Uses private class attributes `_numerator` and `_denominator` in place of the `numerator` and `denominator` property accesses. Co-authored-by: hauntsaninja <hauntsaninja@gmail.com>
* gh-100488: Add is_integer method to fractions.Fraction (#100489)Shantanu2023-01-011-0/+4
|
* GH-96465: Cache hashes for Fraction instances (GH-96483)Raymond Hettinger2022-09-071-30/+35
|
* Allow whitespace around a slash in fraction string inputs (GH-96496)Raymond Hettinger2022-09-021-1/+1
|
* Minor optimization for Fractions.limit_denominator (GH-93730)Mark Dickinson2022-06-211-6/+8
| | | | | | | | | | When we construct the upper and lower candidates in limit_denominator, the numerator and denominator are already relatively prime (and the denominator positive) by construction, so there's no need to go through the usual normalisation in the constructor. This saves a couple of potentially expensive gcd calls. Suggested by Michael Scott Asato Cuthbert in GH-93477.
* bpo-44547: Make Fractions objects instances of typing.SupportsInt (GH-27851)Mark Dickinson2021-10-211-1/+8
| | | Co-authored-by: Łukasz Langa <lukasz@langa.pl>
* bpo-44258: support PEP 515 for Fraction's initialization from string (GH-26422)Sergey B Kirpichev2021-06-071-10/+11
| | | | | | | | | | | | | | | | | | | * bpo-44258: support PEP 515 for Fraction's initialization from string * regexps's version * A different regexps version, which doesn't suffer from catastrophic backtracking * revert denom -> den * strip "_" from the decimal str, add few tests * drop redundant tests * Add versionchanged & whatsnew entry * Amend Fraction constructor docs * Change .. versionchanged:...
* Trivial change in fractions module docs: real -> rational numbers (GH-25009)Sergey B Kirpichev2021-05-291-1/+1
| | | | | Obviously, the former was a little misleading: not only rationals may be considered as "infinite-precision, real numbers" - but, for example, any real finite extension of the rationals.
* bpo-44154: optimize Fraction pickling (GH-26186)Sergey B Kirpichev2021-05-171-1/+1
|
* bpo-43420: Simple optimizations for Fraction's arithmetics (GH-24779)Sergey B Kirpichev2021-03-221-9/+116
| | | | | | | bpo-43420: Implement standard transformations in + - * / that can often reduce the size of intermediate integers needed. For rationals with large components, this can yield dramatic speed improvements, but for small rationals can run 10-20% slower, due to increased fixed overheads in the longer-winded code. If those slowdowns turn out to be a problem, see the PR discussion for low-level implementation tricks that could cut other fixed overheads. Co-authored-by: Tim Peters <tim.peters@gmail.com> Co-authored-by: Mark Dickinson <dickinsm@gmail.com>
* bpo-39350: Fix fractions for int subclasses (GH-18375)Victor Stinner2020-02-071-7/+3
| | | | | | | Fix regression in fractions.Fraction if the numerator and/or the denominator is an int subclass. The math.gcd() function is now used to normalize the numerator and denominator. math.gcd() always return a int type. Previously, the GCD type depended on numerator and denominator.
* bpo-39274: Ensure Fraction.__bool__() returns a bool (GH-18017)Sebastian Berg2020-02-061-1/+3
| | | | | Some numerator types used (specifically NumPy) decides to not return a Python boolean for the "a != b" operation. Using the equivalent call to bool() guarantees a bool return also for such types.
* bpo-39350: Remove deprecated fractions.gcd() (GH-18021)Victor Stinner2020-01-161-23/+1
| | | | Remove fractions.gcd() function, deprecated since Python 3.5 (bpo-22486): use math.gcd() instead.
* Add a minor `Fraction.__hash__()` optimization (GH-15313)Tim Peters2019-08-171-2/+17
| | | | | | * Add a minor `Fraction.__hash__` optimization that got lost in the shuffle. Document the optimizations.
* bpo-37863: Optimize Fraction.__hash__() (#15298)Raymond Hettinger2019-08-161-15/+11
|
* bpo-37819: Add Fraction.as_integer_ratio() (GH-15212)Raymond Hettinger2019-08-111-0/+8
|
* bpo-36625: Remove obsolete comments from docstrings in fractions module ↵Jakub Molinski2019-04-151-3/+3
| | | | | (GH-12822) Remove left-over references to Python 3.0 as the future in Fraction class docstrings.
* bpo-35588: Speed up mod, divmod and floordiv operations for Fraction type ↵Stefan Behnel2019-01-021-3/+11
| | | | | | | | | | | | | | | | | | | | | | | | | | | | | | (#11322) * bpo-35588: Implement mod and divmod operations for Fraction type by spelling out the numerator/denominator calculation, instead of instantiating and normalising Fractions along the way. This speeds up '%' and divmod() by 2-3x. * bpo-35588: Also reimplement Fraction.__floordiv__() using integer operations to make it ~4x faster. * Improve code formatting. Co-Authored-By: scoder <stefan_ml@behnel.de> * bpo-35588: Fix return type of divmod(): the result of the integer division should be an integer. * bpo-35588: Further specialise __mod__() and inline the original helper function _flat_divmod() since it's no longer reused. * bpo-35588: Add some tests with large numerators and/or denominators. * bpo-35588: Use builtin "divmod()" function for implementing __divmod__() in order to simplify the implementation, even though performance results are mixed. * Rremove accidentally added empty line. * bpo-35588: Try to provide more informative output on test failures. * bpo-35588: Improve wording in News entry. Co-Authored-By: scoder <stefan_ml@behnel.de> * Remove stray space.
* bpo-32968: Make modulo and floor division involving Fraction and float ↵Elias Zamaria2018-08-271-9/+4
| | | | | | | consistent with other operations (#5956) Make mixed-type `%` and `//` operations involving `Fraction` and `float` objects behave like all other mixed-type arithmetic operations: first the `Fraction` object is converted to a `float`, then the `float` operation is performed as normal. This fixes some surprising corner cases, like `Fraction('1/3') % inf` giving a NaN. Thanks Elias Zamaria for the patch.
* Issue #27832: Make _normalize parameter to Fraction.__init__ keyword-only.Mark Dickinson2016-08-231-1/+1
|
* Issue #27539: Merge from 3.5.Mark Dickinson2016-08-221-1/+5
|\
| * Issue #27539: Fix unnormalised Fraction.__pow__ result for negative exponent ↵Mark Dickinson2016-08-221-1/+5
| | | | | | | | and base. Thanks Vedran Čačić.
* | Issue #25971: Optimized creating Fractions from floats by 2 times and fromSerhiy Storchaka2015-12-291-28/+4
|/ | | | | | Decimals by 3 times. Unified error messages in float.as_integer_ratio(), Decimal.as_integer_ratio(), and Fraction constructors.
* Issue #22486: Added the math.gcd() function. The fractions.gcd() function ↵Serhiy Storchaka2015-05-121-2/+19
| | | | | | now is deprecated. Based on patch by Mark Dickinson.
* #22464: Speed up common Fraction operations by special-casing severalGeorg Brandl2014-09-241-7/+17
| | | | | | operations for int-type arguments: constructor and equality test. Also avoid redundant property lookups in addition and subtraction.
* Issue #22033: Reprs of most Python implemened classes now contain actualSerhiy Storchaka2014-07-251-1/+2
| | | | class name instead of hardcoded one.
* Issue #21136: Avoid unnecessary normalization in Fractions resulting from ↵Mark Dickinson2014-04-051-9/+14
| | | | power and other operations.
* Issue #16469: Fraction(float('nan')) and Fraction(float('inf')) now raise ↵Mark Dickinson2012-11-151-5/+9
| | | | ValueError and OverflowError (resp.), not TypeError.
* Make Fraction(-1).__hash__() return -2 rather than -1 (see issue 10356).Mark Dickinson2010-11-131-6/+3
|
* Issue #8188: Introduce a new scheme for computing hashes of numbersMark Dickinson2010-05-231-9/+22
| | | | | | (instances of int, float, complex, decimal.Decimal and fractions.Fraction) that makes it easy to maintain the invariant that hash(x) == hash(y) whenever x and y have equal value.
* Merged revisions 79629 via svnmerge fromMark Dickinson2010-04-031-8/+54
| | | | | | | | | | svn+ssh://pythondev@svn.python.org/python/trunk ........ r79629 | mark.dickinson | 2010-04-02 23:27:36 +0100 (Fri, 02 Apr 2010) | 2 lines Issue #8294: Allow float and Decimal arguments in Fraction constructor. ........
* Merged revisions 79455 via svnmerge fromMark Dickinson2010-03-271-2/+0
| | | | | | | | | | svn+ssh://pythondev@svn.python.org/python/trunk ........ r79455 | mark.dickinson | 2010-03-27 11:09:29 +0000 (Sat, 27 Mar 2010) | 2 lines Make Fraction to complex comparisons with <=, <, >= or > raise TypeError. ........
* Merged revisions 76456 via svnmerge fromMark Dickinson2009-11-231-2/+2
| | | | | | | | | | svn+ssh://pythondev@svn.python.org/python/trunk ........ r76456 | mark.dickinson | 2009-11-23 16:23:43 +0000 (Mon, 23 Nov 2009) | 2 lines Issue #7379: Fix incorrect doctest for Fraction.limit_denominator. ........
* Issue #6431: Fix Fraction comparisons to return NotImplemented whenMark Dickinson2009-07-181-30/+32
| | | | | | the Fraction type doesn't know how to handle the comparison without loss of accuracy. Also, make sure that comparisons between Fractions and float infinities or nans do the right thing.
* - remove svn:executable property from some library filesMatthias Klose2009-06-221-0/+0
|
* Merged revisions 71832 via svnmerge fromMark Dickinson2009-04-241-12/+21
| | | | | | | | | | | svn+ssh://pythondev@svn.python.org/python/trunk ........ r71832 | mark.dickinson | 2009-04-24 14:56:07 +0100 (Fri, 24 Apr 2009) | 3 lines Issue #5812: The two-argument form of the Fraction constructor now accepts arbitrary Rational instances. ........
* Issue #5812: Make Fraction('1e6') valid. The Fraction constructor nowMark Dickinson2009-04-221-19/+26
| | | | | accepts all strings accepted by the float and Decimal constructors, with the exception of strings representing NaNs or infinities.
* Manually merge r68096,68189 from 3.0 branch.Georg Brandl2009-01-031-1/+1
|