Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python 2.7.3 hash strings used to seed random number generators?

In 64 bit Python 2.7.6 this is True, however in 32 bit Python 2.7.3 it is False:

random.Random(hash("a")).random() == random.Random("a").random()

So how does Python 2.7.3 hash strings used to seed random number generators?

like image 598
Nathan Breit Avatar asked Apr 24 '14 06:04

Nathan Breit


1 Answers

it's because on 32bit hash("a") is a negative number (because of platform long type size) and the random modules behaves differently.

The random module seed() function:

  • passing int or long it will use PyNumber_Absolute() that is abs()
  • passing an object (a string) it will use PyLong_FromUnsignedLong((unsigned long)hash)

sign bit truncation and abs give different result

e.g.:

  • abs(-10) = 10
  • ((unsigned long) -10) = 4294967286
like image 61
sherpya Avatar answered Nov 01 '22 16:11

sherpya