Consider this division in Python:
Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 2/2
1.0
Is this intended? I strongly remember earlier versions returning int/int = int. What should I do? Is there a new division operator or must I always cast?
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Take a look at PEP-238: Changing the Division Operator
The // operator will be available to request floor division unambiguously.
Method 2
Oops, immediately found 2//2. This will output an int rather than a float.
Method 3
Behavior of the division operator in Python 2.7 and Python 3
In Python 2.7: By default, division operator will return integer output.
To get the result in double, multiply the dividend or divisor by 1.0.
100/35 => 2 # Expected is 2.857142857142857
(100*1.0)/35 => 2.857142857142857
100/(35*1.0) => 2.857142857142857
In Python 3
// => used for integer output
/ => used for double output
100/35 => 2.857142857142857
100//35 => 2
100.//35 => 2.0 # Floating-point result if the divisor or dividend is real
Method 4
The accepted answer already mentions PEP 238. I just want to add a quick look behind the scenes for those interested in what’s going on without reading the whole PEP.
Python maps operators like +, -, * and / to special functions, such that e.g. a + b is equivalent to
a.__add__(b)
Regarding division in Python 2, there is by default only / which maps to __div__ and the result is dependent on the input types (e.g. int, float).
Python 2.2 introduced the __future__ feature division, which changed the division semantics the following way (TL;DR of PEP 238):
/maps to__truediv__which must “return a reasonable approximation of
the mathematical result of the division” (quote from PEP 238)//maps to__floordiv__, which should return the floored result of/
With Python 3.0, the changes of PEP 238 became the default behaviour and there is no more special method __div__ in Python’s object model.
If you want to use the same code in Python 2 and Python 3 use
from __future__ import division
and stick to the PEP 238 semantics of / and //.
Method 5
According to Python 3 documentation, Python when divided by integer, will generate float despite expected to be integer.
For exclusively printing integer,use floor division method.
Floor division is rounding off zero and removing decimal point. Represented by //
Hence, instead of 2/2 ,use 2//2
You can also import division from __future__ irrespective of using Python 2 or Python 3.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0