简体   繁体   中英

python division result different with negative number

While playing with python command line I notice the following:

Python 2.7.3 |EPD_free 7.3-2 (64-bit)| (default, Apr 11 2012, 17:52:16)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-44)] on linux2
Type "credits", "demo" or "enthought" for more information.
>>> 9/7
1
>>> -9/7
-2
>>>

Could someone indicate why my answer is different with negative number division? Thanks.

In Python 2.X, / is actually floor division for ints and longs:

The current division (/) operator has an ambiguous meaning for numerical arguments: it returns the floor of the mathematical result of division if the arguments are ints or longs, but it returns a reasonable approximation of the division result if the arguments are floats or complex. This makes expressions expecting float or complex results error-prone when integers are not expected but possible as inputs. [source: PEP 238]

If you want to use true division with ints/longs, you can add from __future__ import division to your module (or by switching to 3.X). If you do this, you can use floor division by doing x//y .

>>> 9/7
1
>>> -9/7
-2
>>> from __future__ import division
>>> 9/7
1.2857142857142858
>>> -9/7
-1.2857142857142858

因为整数除法四舍五入到最接近的较低整数。

It's like the Floor and ceiling functions , you will get that because you're using integer numbers

You can try the int() function if you want it to be "equal" in terms of values, like this

>>> int(9/7.0)
1
>>> int(-9/7.0)
-1

You can put one or both of the numbers with the ".0" in order to get a floating point

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM