如何在python中重用单个random()实例

2024-06-09 02:46:53 发布

您现在位置:Python中文网/ 问答频道 /正文

jvm(scala、java、kotlin、jruby等)上,以下结果产生一个单一变量,该变量被反复查询以获得新的随机值:

IntStream.range(0,10).forEach( __ -> System.out.println(rand.nextFloat()));

python中是否有一个与next[Float | Double | Int]等价的函数?如果不是,调用时引擎盖下会发生什么

import random
for i in range(10):
   print(str(random.random()))

{}库本身是否持有一个随机引用?如果没有,那么如何确保避免重复,比如说在几微秒内运行多次迭代?我假设系统时钟与随机数发生器有关


Tags: rangerandomjvmjavaoutsystemnextscala
3条回答

从源头上说,

#                                    
# Create one instance, seeded from current time, and export its methods
# as module-level functions.  The functions share state across all uses
# (both in the user's code and in the Python libraries), but that's fine
# for most programs and is easier for the casual user than making them
# instantiate their own Random() instance.

_inst = Random()
seed = _inst.seed
random = _inst.random

所以它创建了一个随机实例

https://github.com/python/cpython/blob/3.9/Lib/random.py

是的,random库保存着伪随机生成器的单个实例。从docs开始:

The functions supplied by this module are actually bound methods of a hidden instance of the random.Random class. You can instantiate your own instances of Random to get generators that don’t share state.

是的,系统时钟用于为RNG播种,除非操作系统提供更好的功能:

If a is omitted or None, the current system time is used. If randomness sources are provided by the operating system, they are used instead of the system time (see the os.urandom() function for details on availability).

碰巧random模块中的所有可调用项都是函数,人们可以终生编写Python代码,而不知道在这种特定情况下,与其他模块不同,这些可调用项是random.Random()单个实例的别名

所以,简而言之,“随机库本身是否持有一个随机引用?”。是的,它在随机模块上作为random._inst,并且在random.py模块文件的最后一行,这个实例上的方法被别名为模块级可调用函数(带有一堆randint = _inst.randint语句)

这种设计的一个有趣之处是,虽然_inst和默认可调用项是random.Random的实例,但随机模块还提供了SystemRandom类,该类使用O.S.随机数生成器作为源,在大多数情况下,它的一个实例可以使用高级方法作为可靠的随机数生成器,而不必依赖os.urandom()提供的原始字节

相关问题 更多 >