python random设置种子_python - 如何查询random.random()使用的种子? - 堆栈内存溢出...

您可以继承random.Random的子类,以与python相同的方式(在本示例中为v3.5)重写seed()方法,但在调用super()之前将种子值存储在变量中:

import random

class Random(random.Random):

def seed(self, a=None, version=2):

from os import urandom as _urandom

from hashlib import sha512 as _sha512

if a is None:

try:

# Seed with enough bytes to span the 19937 bit

# state space for the Mersenne Twister

a = int.from_bytes(_urandom(2500), 'big')

except NotImplementedError:

import time

a = int(time.time() * 256) # use fractional seconds

if version == 2:

if isinstance(a, (str, bytes, bytearray)):

if isinstance(a, str):

a = a.encode()

a += _sha512(a).digest()

a = int.from_bytes(a, 'big')

self._current_seed = a

super().seed(a)

def get_seed(self):

return self._current_seed

如果您对其进行测试,则使用新种子生成的第一个随机值和使用相同种子(使用我们创建的get_seed()方法生成)的第二个值将相等:

>>> rnd1 = Random()

>>> seed = rnd1.get_seed()

>>> v1 = rnd1.randint(1, 0x260)

>>> rnd2 = Random(seed)

>>> v2 = rnd2.randint(1, 0x260)

>>> v1 == v2

True

如果存储/复制巨大的种子值并尝试在另一个会话中使用它,则生成的值将完全相同。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值