[Python-ideas] integer dividion in R -- PS

Mark Dickinson dickinsm at gmail.com
Fri May 7 11:43:20 CEST 2010


On Fri, May 7, 2010 at 9:19 AM, Xavier Ho <contact at xavierho.com> wrote:
> 2010/5/7 spir ☣ <denis.spir at gmail.com>
>>
>> The following discussion in the article does not tell whether one solution
>> is the _official_ one.
>> But: that   -4/3 != -(4/3)   looks simply wrong for me.
>>
>> Denis
>
> I believe the official decision relates to PEP 238:

No: PEP 238 is (partly) about how integer division is expressed in
Python;  not about its semantics.  Python's choice for integer
division with negative arguments goes back much further.  From
Misc/HISTORY:

==================================
==> RELEASE 0.9.6 (6 Apr 1992) <==
==================================

[...]

New features in 0.9.6:

[...]

- Division and modulo for long and plain integers with negative operands
  have changed; a/b is now floor(float(a)/float(b)) and a%b is defined
  as a-(a/b)*b.  So now the outcome of divmod(a,b) is the same as
  (a/b, a%b) for integers.  For floats, % is also changed, but of course
  / is unchanged, and divmod(x,y) does not yield (x/y, x%y)...
[...]


Personally, I've always liked Python's behaviour in this regard:  for
the few times that I've needed an 'x % y' operation that works with
both positive and negative x, more often than not x-y*floor(x/y) turns
out to be what I need.  I've lost count of the number times I've had
to write something awkward like:

	/* adjust for the exponent;  first reduce it modulo _PyHASH_BITS */
	e = e >= 0 ? e % _PyHASH_BITS : _PyHASH_BITS-1-((-1-e) % _PyHASH_BITS);

in C.

-- 
Mark



More information about the Python-ideas mailing list