The REALLY bad thing about Python lists ..

Russell Wallace rwallace at esatclear.ie
Wed May 24 17:24:39 EDT 2000


Greg Ewing wrote:
> 
> Russell Wallace wrote:
> >
> > (Under what circumstances would you want to use % on negative numbers?
> > I can't think of any.)
> 
> Here's a couple:
> 
> 1) Consider a tile-based game in which the player walks around
> on a grid of cells of size s by s. Given the pixel coordinates
> (x, y) of the player, the cell coordinates are (x div s, y div s)
> and the location within the cell is (x mod s, y mod s).
> 
> If div and mod are defined appropriately, it doesn't matter
> where abouts in the grid the origin is. This may be useful,
> for example if you want to simulate an infinite world by
> automatically extending the grid when the player walks off
> the edge. If coordinates are restricted to positive numbers,
> it becomes somewhat more complicated to do that.

True.  I just can't imagine doing that by taking the mod of negative
numbers, rather than explicitly converting them to positive numbers
first.

> 2) This one actually bit me in real life: Many years ago,
> in Lightspeed Pascal on the Mac, I got into the habit of using
> 'Random mod n' to generate a number from 0 to n-1. Due
> to the way mod was defined, this worked fine, even though
> the Toolbox Random function returns a signed 16-bit integer.
> 
> Then they decided to change mod so that it complied with some
> ANSI Pascal standard or other, and suddenly that didn't work any
> more. I had to use 'abs(Random) mod n' instead, which I
> found less than elegant.

abs(Random) won't work if it happens to return -32768; you want to use
>> 1, & 0x7FFF or (unsigned) instead.  (Or whatever the Pascal equivalents are - I forget which of those it supports.)

But yeah, that's another example - I suppose I think of it like doing
floating point arithmetic by explicitly writing shifts and bitwise & and
| operations; yes I can think of occasions on which it would work and be
more efficient than the alternative; but I can't imagine being confident
enough about the clarity and portability of the resulting code to
actually do it.  Honestly, right now I have no idea exactly what mod
should return in the cases you outline above; I'd have to carefully work
out the logic on paper and then run tests to make sure there wasn't an
error in my logic.  I've even seen mathematicians disagree with each
other on what mod of negative numbers should return.  So for a language
to mandate it strikes me as kind of like a language mandating the bit
format of floating point numbers.

-- 
"To summarize the summary of the summary: people are a problem."
Russell Wallace
mailto:rwallace at esatclear.ie
http://www.esatclear.ie/~rwallace



More information about the Python-list mailing list