If one of the operands in you division is a float and the other one is a whole number ( int , long , etc), your result's gonna be floating-point. This means, this will be a floating-point division: if you divide 5 by 2, you get 2.5 as expected.
Behavior of the division operator in Python 2.7 and Python 3 // is not "used for integer output". // is the result of the floor() function to the result of the division, which in turns yields an integer if the two operands are integers and a float if at least one of them is a float, for types coherence.
The numeric arguments are first converted to a common type. Division of integers yields a float, while floor division of integers results in an integer; the result is that of mathematical division with the 'floor' function applied to the result. The result of flooring is safe to convert to an integer.
Dividing two integers will result in an integer (whole number) result. You need to cast one number as a float, or add a decimal to one of the numbers, like a/350.0.
Take a look at PEP-238: Changing the Division Operator
The // operator will be available to request floor division unambiguously.
Oops, immediately found 2//2
. This will output an int rather than a float.
In Python 2.7: By default, division operator will return integer output.
To get the result in double multiple 1.0 to "dividend or divisor"
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 divsor or dividend real
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 //
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With