简体   繁体   English

为什么random.random()会占用两个random.randint()值?

[英]Why does random.random() take up two random.randint() values?

I've developed a simple application that generates test data series and I've built it to be able to be repeatable, using a random seed. 我开发了一个生成测试数据系列的简单应用程序,并且我使用随机种子构建它以便能够重复。 I noticed the following and wanted to know why this happens: 我注意到以下内容并想知道为什么会发生这种情况:

>>> random.seed(1)
>>> [random.randint(0,10) for _ in range(0,10)]
[2, 9, 1, 4, 1, 7, 7, 7, 10, 6]
>>> random.seed(1)
>>> random.random()
0.13436424411240122
>>> [random.randint(0,10) for _ in range(0,10)]
[1, 4, 1, 7, 7, 7, 10, 6, 3, 1]

Note how a single call to random() uses up two values for randint(). 注意对random()的单个调用如何使用randint()的两个值。 I'm guessing this has something to do with the amount of random information required to generate a float vs. an int in the given range, but is there some way of keeping track of 'how many random values have been used so far?', ie how far along in the sequence of semi-random values the system is? 我猜这与在给定范围内生成浮点数与int值所需的随机信息量有关,但是有没有办法跟踪到目前为止使用了多少随机值? ,即系统的半随机值序列有多远?

I ended up writing my own function, always using a single call to random.random() in its logic. 我最终编写了自己的函数,总是在其逻辑中使用random.random()。 So I'm not asking for a solution, just some background / an explanation. 所以我不是要求解决方案,只是一些背景/解释。

Your guess is accurate, at least for the latest version of CPython. 您的猜测是准确的,至少对于最新版本的CPython。 There are a couple of relevant places in the code for the random module where you can see why this is happening. 随机模块的代码中有几个相关的位置,您可以在其中看到为什么会发生这种情况。 I would consider all of this an implementation detail, but you can see that essentially, groups of 32 random bits are generated as needed to get random numbers. 我会考虑所有这些实现细节,但是你可以看到,基本上,根据需要生成32个随机位的组以获得随机数。 For this reason, getting 53 random bits (to represent the fractional part of a double) uses twice as many random bits as getting 4 random bits. 因此,获得53个随机位(表示双精度的小数部分)使用的随机位数是获得4个随机位的两倍。

With respect to being able to tell how much random data has been generated, the provided functions don't seem to give you an easy and reliable way of doing that. 关于能够分辨出已经生成了多少随机数据,所提供的功能似乎并没有为您提供简单可靠的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM