Integer Overflow
Gareth McCaughan
Gareth.McCaughan at pobox.com
Tue Nov 27 17:15:05 EST 2001
"Ursus Horibilis" wrote:
> unsigned int Lcprng(unsigned int *seed)
> {
> *seed = 29 * (*seed) + 13;
> return (*seed);
> }
>
> How do you do this in Python?
def Lcprng(state):
"""Pass this a list containing just the seed. It will be updated,
and the value inside returned."""
state[0] = (29*seed[0]+13) & 0xFFFFFFFFL
return state[0]
Points to note:
- using a 1-element list is about the nearest equivalent
we have to passing in a pointer as your C code does.
It's not necessarily good style (but then, neither is
the pointer-passing thing).
- After one iteration, the value in "state" will be a
long integer and there will therefore be no danger
of overflow. But you should make sure you start it
off with a long anyway.
By the way, that's not a very good random number generator. :-)
--
Gareth McCaughan Gareth.McCaughan at pobox.com
.sig under construc
More information about the Python-list
mailing list