faqts : Computers : Programming : Languages : Python : Common Problems : Maths : Random Numbers

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

3 of 3 people (100%) answered Yes
Recently 1 of 1 people (100%) answered Yes

Entry

How can I generate long (uniformly distributed) random integers?

Aug 21st, 2000 19:13
unknown unknown, Tim Roberts, Pat McCann


Problem:
Does anyone know of an easy way to generate long (uniformely 
distributed) random integers, for example, I'd like to be able to write
generator = whrandom.whrandom()
N = generator.randint(1L,
987349857349878957987598743987587598374985739847589L)
Solution:
It is not hard to write a linear congruential random number generator, 
like that used in most run-time libraries.  Here's one that can 
generate 128-bit values:
class BigRand:
  RandSeed = 11111111111111111111111111111111111L
  def Rand(self):
    hold = self.RandSeed
    self.RandSeed = (self.RandSeed * 134775813L + 1L) % (2L**128L)
    return hold
r = BigRand()
for i in range(20):
  print r.Rand()
And a small tip:
If you need multiple streams of random numbers, get them out of one
number generator, instead of one per stream, to avoid the (VERY small)
chance that the streams will be sequence-shifted versions of each other.
Also, check out the answer, that was originally archived in Hans 
Nowak's snippets collection, from Tim Peters:
LongRan - Long random number generator
http://www.faqts.com/knowledge-base/view.phtml/aid/4406/fid/546