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: strange arithmetic behaviour
Type: behavior Stage:
Components: None Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: alexey.radkov, mark.dickinson
Priority: normal Keywords:

Created on 2010-11-07 10:40 by alexey.radkov, last changed 2022-04-11 14:57 by admin. This issue is now closed.

Messages (2)
msg120665 - (view) Author: Alexey Radkov (alexey.radkov) Date: 2010-11-07 10:40
The following excerpt will show the issue:

$ python
Python 2.7 (r27:82500, Sep 16 2010, 18:02:00) 
[GCC 4.5.1 20100907 (Red Hat 4.5.1-3)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 8 * 4 / ( 2 - 7 ) * 6 / 3
-14
>>>

Why it is evaluated to -14 ?? In floating point arithmetic it should be -12.8, in integer arithmetic i believe it should be -12 (at least bc and a small dedicated C program evaluate it to -12). Perhaps i do not understand some specific python arithmetic priority or associativity rules, anyway i cannot find a specific combinations of them to yield -14 in this expression.
msg120667 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2010-11-07 10:51
It's not a bug:  you're seeing Python's rules for integer division, which do indeed differ from those of (some) other languages when either the divisor or the dividend is negative.  For integers x and y, in Python 2.x, x / y gives the floor of the exact quotient.

>>> -32 / 5
-7
>>> 32 / -5
-7

In Python 3.x, the '/' operator does 'true division', giving you (a floating-point approximation to) the true result:

>>> -32 / 5
-6.4
>>> 32 / -5
-6.4

You can also get this behaviour in Python 2.x if you start your script with 'from __future__ import division'.

See the documentation at:

http://docs.python.org/reference/expressions.html#binary-arithmetic-operations

for more.
History
Date User Action Args
2022-04-11 14:57:08adminsetgithub: 54555
2010-11-07 10:51:26mark.dickinsonsetstatus: open -> closed

nosy: + mark.dickinson
messages: + msg120667

resolution: not a bug
2010-11-07 10:40:18alexey.radkovcreate