[Python-ideas] integer dividion in R -- PS
Jason Orendorff
jason.orendorff at gmail.com
Fri May 7 16:20:14 CEST 2010
2010/5/7 spir ☣ <denis.spir at gmail.com>:
> I searched the def of int division in R. I could not find it in the english wikipedia,
On page 4 of Gallian, "Contemporary Abstract Algebra", we have:
Division Algorithm
Let a and b be integers with b > 0. Then there exist unique
integers q and r with the property that a = bq + r where
0 <= r < b.
This is, of course, the definition Python uses. I think this is pretty
standard. What might mathematicians like about this definition? Well,
I think the fundamentally important thing about integer division (or
any mathematical object really) is the patterns it makes:
>>> [a % 5 for a in range(20)]
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
>>> [a // 5 for a in range(20)]
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3]
Those patterns show up in both C and Python. Do the patterns continue
as you go into the negative numbers? In Python they do:
>>> [a % 5 for a in range(-10, 10)]
[0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4]
>>> [a // 5 for a in range(-10, 10)]
[-2, -2, -2, -2, -2, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1]
In C, the patterns change as you pass 0.
That is, the Python definition satisfies these mathematical
properties, and the C definition doesn't:
(a + b) // b == a // b + 1
(a + b) % b == a % b
The Python definition agrees with modulo arithmetic:
-3 ≡ 2 (mod 5)
http://en.wikipedia.org/wiki/Modular_arithmetic
In Python, -3 % 5 == 2 % 5 is true. In C it is false.
> But: that -4/3 != -(4/3) looks simply wrong for me.
You can either have the mirror symmetry about 0 that you want, or you
can have the translational symmetry shown above. I think translational
symmetry is the defining thing about integer division and therefore
more important.
Of course for a programming language the question of which definition
to use is a practical one: which is more useful? Ultimately
practicality beats purity. But as far as purity goes (and it goes
along with practicality a good long way) I think Python's integer
division wins by a wide margin.
Cheers,
-j
More information about the Python-ideas
mailing list