在python或它的包装器中是否有任何drand48()等效?

Sha*_*han 1 python random

我正在将一些c代码转换为python.我想知道在python中是否有任何drand48()等效(完全相同!)或它的包装?

非常感谢

Die*_*Epp 7

你在找random.random.

>>> import random
>>> help(random)
>>> random.random()
0.8423026866867628
Run Code Online (Sandbox Code Playgroud)

它不使用相同的发电机drand48.该drand48系列使用48位线性同余生成器,而Python随机模块使用优越的Mersenne Twister算法.

如果你想要完全相同的输出drand48,你可以用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   
Run Code Online (Sandbox Code Playgroud)

但是,输出将远远低于Python的标准随机数生成器.rand48SVID 3于1989年宣布该系列功能已过时.

  • @Akaisteph7:已​​经过去了大约10年了,所以我不记得了!glibc 代码需要一些时间来适应,但我想我实际上是从手册页实现的,手册页指定了确切的算法。 (2认同)