This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: round(x,y) doesn't behave as expected, round error
Type: Stage:
Components: Interpreter Core Versions: Python 2.5
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: amaury.forgeotdarc, shlomoa
Priority: normal Keywords:

Created on 2007-12-07 09:30 by shlomoa, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (4)
msg58266 - (view) Author: Shlomo Anglister (shlomoa) Date: 2007-12-07 09:30
#Round is unexpectedly wrong
>>> z = complex(1,1)
>>> s=abs(z)
>>> round(s,2)
1.4099999999999999
msg58267 - (view) Author: Amaury Forgeot d'Arc (amaury.forgeotdarc) * (Python committer) Date: 2007-12-07 09:46
Please see
http://www.python.org/doc/faq/general/#why-are-floating-point-calculations-so-inaccurate
msg58268 - (view) Author: Shlomo Anglister (shlomoa) Date: 2007-12-07 10:04
>>> def my_round(n,i):
...     t = n * (10**i)
...     s = round(t)
...     r = s / (10**i)
...     return r
... 
>>> print my_round(s,2)
1.41
msg58269 - (view) Author: Amaury Forgeot d'Arc (amaury.forgeotdarc) * (Python committer) Date: 2007-12-07 10:13
Your function is not better:

>>> print my_round(s,2)
1.41
>>> my_round(s,2)
1.4099999999999999

print uses str(), and restricts itself to 12 significant digits.
the direct call uses repr(), and display the most precise number.

The problem is not in the computation, but is inherent to the 'float'
type which cannot represent 1.41 exactly. Please carefully read the faq
entry above.
History
Date User Action Args
2022-04-11 14:56:28adminsetgithub: 45906
2007-12-07 10:13:48amaury.forgeotdarcsetmessages: + msg58269
2007-12-07 10:04:55shlomoasetmessages: + msg58268
2007-12-07 09:46:37amaury.forgeotdarcsetstatus: open -> closed
resolution: not a bug
messages: + msg58267
nosy: + amaury.forgeotdarc
2007-12-07 09:30:33shlomoacreate