Skip to content

mpf.__round__() returns mpf#826

Merged
skirpichev merged 1 commit intompmath:masterfrom
skirpichev:round-455
Sep 14, 2024
Merged

mpf.__round__() returns mpf#826
skirpichev merged 1 commit intompmath:masterfrom
skirpichev:round-455

Conversation

@skirpichev
Copy link
Copy Markdown
Collaborator

@skirpichev skirpichev commented Aug 1, 2024

Probably this will look non-intuitive, but underlying floating-point arithmetic is binary, not decimal. Thus, round(x, n) sometimes will pick up a decimal representation with more than n digits. This is something common for CPython < 2.7 and < 3.1:

Python 2.6.6 (r266:84292, Aug 12 2014, 07:57:07) [GCC 4.4.5] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> round(0.42754287856598971, 2)
0.42999999999999999

And with this patch as well:

Python 3.12.5+ (heads/3.12:0181aa2e3e, Aug 29 2024, 14:55:08) [GCC 12.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from mpmath import *
>>> round(mp.mpf(0.42754287856598971), 2)
mpf('0.42999999999999999')
>>> mp.pretty = True
>>> round(mp.mpf(0.42754287856598971), 2)
0.43

See also python/cpython#45921

Closes #455

Probably this will look non-intuitive, but underlying floating-point
arithmetic is binary, not decimal.  Thus, round(x, n) sometimes will pick
up a decimal representation with more than n digits.  This is something
common for CPython < 2.7 and < 3.1:

    Python 2.6.6 (r266:84292, Aug 12 2014, 07:57:07)
    [GCC 4.4.5] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> round(0.42754287856598971, 2)
    0.42999999999999999

And with this patch as well:

    Python 3.12.5+ (heads/3.12:0181aa2e3e, Aug 29 2024, 14:55:08) [GCC 12.2.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from mpmath import *
    >>> round(mp.mpf(0.42754287856598971), 2)
    mpf('0.42999999999999999')
    >>> mp.pretty = True
    >>> round(mp.mpf(0.42754287856598971), 2)
    0.43

See also python/cpython#45921

Closes mpmath#455
@skirpichev skirpichev marked this pull request as ready for review September 7, 2024 04:43
@skirpichev
Copy link
Copy Markdown
Collaborator Author

I'm going to merge this after a week. But I would appreciate @cbm755 feedback, as new feature might look surprising.

@skirpichev skirpichev merged commit 21fed47 into mpmath:master Sep 14, 2024
@skirpichev skirpichev deleted the round-455 branch September 14, 2024 03:32
@skirpichev skirpichev added this to the 1.4 milestone May 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

rounding in Python 3 need not return a float

1 participant