python / cpython

The Python programming language
https://www.python.org
Other
63.18k stars 30.25k forks source link

Division Precision Problem #80836

Closed 4e360ee3-b6e5-4384-b0fb-eef351f1b0b0 closed 5 years ago

4e360ee3-b6e5-4384-b0fb-eef351f1b0b0 commented 5 years ago
BPO 36655
Nosy @ericvsmith, @tiran, @クロポ

Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.

Show more details

GitHub fields: ```python assignee = None closed_at = created_at = labels = ['invalid', 'type-bug', '3.7'] title = 'Division Precision Problem' updated_at = user = 'https://bugs.python.org/kulopo' ``` bugs.python.org fields: ```python activity = actor = 'eric.smith' assignee = 'none' closed = True closed_date = closer = 'christian.heimes' components = [] creation = creator = 'kulopo' dependencies = [] files = [] hgrepos = [] issue_num = 36655 keywords = [] message_count = 3.0 messages = ['340471', '340472', '340473'] nosy_count = 3.0 nosy_names = ['eric.smith', 'christian.heimes', 'kulopo'] pr_nums = [] priority = 'normal' resolution = 'not a bug' stage = 'resolved' status = 'closed' superseder = None type = 'behavior' url = 'https://bugs.python.org/issue36655' versions = ['Python 3.7'] ```

4e360ee3-b6e5-4384-b0fb-eef351f1b0b0 commented 5 years ago
>>> a=224847175712806907706081280
>>> b=4294967296
>>> assert int(a*b/b)==int(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
(a can be exact divided by b)
tiran commented 5 years ago

This is the expected and correct behavior. Python's float are IEEE 754 floats, https://en.wikipedia.org/wiki/IEEE_754. IEE 754 have a limited precision. 224847175712806907706081280 / 4294967296 is not exactly dividable under IEEE 754 semantics.

>>> a=224847175712806907706081280
>>> b=4294967296
>>> a/b
5.235131264496755e+16
ericvsmith commented 5 years ago

Also see https://docs.python.org/3/tutorial/floatingpoint.html for some Python-specific details.