Consistency.
You'll need to follow some very basic and seemingly irrelevant explanations to understand it.
In school you have learned division with a remainder. And you have done calculations like this:
8 ÷ 4 = 2 R 0
7 ÷ 4 = 1 R 3
6 ÷ 4 = 1 R 2
5 ÷ 4 = 1 R 1
4 ÷ 4 = 1 R 0
3 ÷ 4 = 0 R 3
2 ÷ 4 = 0 R 2
1 ÷ 4 = 0 R 1
0 ÷ 4 = 0 R 0
^------ This is the result of x // 4
^-- This is the result of x % 4 (modulo)
Later, you have learned divisions for real numbers:
8 ÷ 4 = 2.0
7 ÷ 4 = 1.75
6 ÷ 4 = 1.5
5 ÷ 4 = 1.25
4 ÷ 4 = 1.0
3 ÷ 4 = 0.75
2 ÷ 4 = 0.5
1 ÷ 4 = 0.25
0 ÷ 4 = 0.0
^--- Note that the number in front of the . is int(x/4)
Until this point, you might believe that x // 4
and int(x/4)
always give the same result. That's your current understanding of the situation.
However, have a look what happens in the integer division: the number behind R cycles from 3, 2, 1 to 0 and then restarts: 3, 2, 1, 0. The number in front of the R decreses every 4th step.
So, how will it go on?
8 ÷ 4 = 2 R 0
7 ÷ 4 = 1 R 3
6 ÷ 4 = 1 R 2
5 ÷ 4 = 1 R 1
4 ÷ 4 = 1 R 0
3 ÷ 4 = 0 R 3
2 ÷ 4 = 0 R 2
1 ÷ 4 = 0 R 1
0 ÷ 4 = 0 R 0
-1 ÷ 4 = -1 R 3
^------ We have to decrease now, because we already have 0 four times
^-- We have to restart the cycle at 3
At the same time, the real number division gives us:
-1 ÷ 4 = -0.25
^----- There is still a 0 in front of the .
That's why -1 // 4
gives -1 but int(-1/4)
gives 0.
Is there any motivation for the differences between the functions?
Well, they serve different purposes: //
is part of an integer calculation with remainders and int()
gives you the part in front of the .
of a real number operation.
You decide what you want to calculate, then you decide which operator to use in Python to get the correct result.
Good question. Keep on learning.
Best Answer
The floating point representation of
10**40//2
is not accurate:That's because floating point arithmetic is only ever an approximation, especially when you go beyond what your CPU can accurately model (as floating point is handled in hardware).
The integer division never has to represent the
10**40
number as a float, it only has to divide the integer, which in Python can be arbitrarily large without precision loss.Also see:
Also look at the
decimal
module if you must use higher-precision floating point arithmetic.