The // “integer division” operator of Python surprised me, today:
>>> math.floor(11/1.1)
10.0
>>> 11//1.1
9.0
The documentation reads “(floored) quotient of x and y”. So, why is math.floor(11/1.1) equal to 10, but 11//1.1 equal to 9?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because 1.1 can’t be represented in binary form exactly; the approximation is a littler higher than 1.1 – therefore the division result is a bit too small.
Try the following:
Under Python 2, type at the console:
In Python 3.1, the console will display
1.1, but internally, it’s still the same number.But:
As gnibbler points out, this is the result of “internal rounding” within the available precision limits of floats. And as The MYYN points out in his comment,
//uses a different algorithm to calculate the floor division result thanmath.floor()in order to preservea == (a//b)*b + a%bas well as possible.Use the
Decimaltype if you need this precision.