I am converting s开发者_高级运维ome c code to python. I am wondering that is there any drand48() equivalent in python(exactly the same!) or a wrapper to it?
Thanks a lot
You are looking for random.random
.
>>> import random
>>> help(random)
>>> random.random()
0.8423026866867628
It does not use the same generator as drand48
. The drand48
family uses a 48-bit linear congruential generator, whereas the Python random module uses the superior Mersenne Twister algorithm.
If you want the exact same output as drand48
, you can implement it in Python.
# Uncomment the next line if using Python 2.x...
# from __future__ import division
class Rand48(object):
def __init__(self, seed):
self.n = seed
def seed(self, seed):
self.n = seed
def srand(self, seed):
self.n = (seed << 16) + 0x330e
def next(self):
self.n = (25214903917 * self.n + 11) & (2**48 - 1)
return self.n
def drand(self):
return self.next() / 2**48
def lrand(self):
return self.next() >> 17
def mrand(self):
n = self.next() >> 16
if n & (1 << 31):
n -= 1 << 32
return n
However, the output will be significantly inferior to Python's standard random number generator. The rand48
family of functions were declared obsolete in 1989 by SVID 3.
精彩评论