an *_*use 0 python random python-3.x
假设我想生成两个随机变量X
,Y
这些变量是不相关的,并且均匀分布在[0,1]
.
生成这样的非常天真的代码是以下,它调用random
函数两次:
import random
xT=0
yT=0
xyT=0
for i in range(20000):
x = random.random()
y = random.random()
xT += x
yT += y
xyT += x*y
xyT/20000-xT/20000*yT/20000
Run Code Online (Sandbox Code Playgroud)
然而,随机数实际上是由公式生成的伪随机数,因此它们是相关的.
如何生成两个不相关(或尽可能少的相关)随机变量?
关于RNG的数学是可靠的.现在最流行的实现也是如此.因此,你猜想的
由公式生成,因此它们是相关的.
是不正确的.
但是,如果你真的非常深思这种方式,那就有一个:硬件随机数生成器.random.org上的网站长期以来一直在提供硬件RNG"即服务".这是一个例子(在R中,我使用了更多,但有一个官方的Python客户端):
R> library(random)
R> randomNumbers(min=1, max=20000) # your range, default number
V1 V2 V3 V4 V5
[1,] 532 19452 5203 13646 5462
[2,] 4611 10814 3694 12731 566
[3,] 11884 19897 1601 10652 791
[4,] 17427 9524 7522 1051 9432
[5,] 5426 5079 2232 2517 4883
[6,] 13807 9194 19980 1706 9205
[7,] 13043 16250 12827 2161 10789
[8,] 7060 6008 9110 8388 1102
[9,] 12042 19342 2001 17780 3100
[10,] 11690 4986 4389 14187 17191
[11,] 19574 13615 3129 17176 5590
[12,] 11104 5361 8000 5260 343
[13,] 7518 7484 7359 16840 12213
[14,] 14914 1991 19952 10127 14981
[15,] 13528 18602 10182 1075 16480
[16,] 9631 17160 19808 11662 10514
[17,] 4827 13960 17003 864 11159
[18,] 8939 7095 16102 19836 15490
[19,] 8321 6007 1787 6113 17948
[20,] 9751 7060 8355 19065 15180
R>
Run Code Online (Sandbox Code Playgroud)
编辑: OP似乎不相信,所以有一个快速可重复的模拟(再次,在R,因为这是我使用的):
R> set.seed(42) # set seed for RNG
R> mean(replicate(10, cor(runif(100), runif(100))))
[1] -0.0358398
R> mean(replicate(100, cor(runif(100), runif(100))))
[1] 0.0191165
R> mean(replicate(1000, cor(runif(100), runif(100))))
[1] -0.00117392
R>
Run Code Online (Sandbox Code Playgroud)
因此,您可以看到,当我们从10到100再到1000次重复仅100 U(0,1)时,相关性估计值变为零.
我们可以通过绘图,恢复相同的数据以及更多:
R> set.seed(42)
R> x <- 10^(1:5) # powers of ten from 1 to 5, driving 10^1 to 10^5 sims
R> y <- sapply(x, function(n) mean(replicate(n, cor(runif(100), runif(100)))))
R> y # same first numbers as seed reset to same start
[1] -0.035839756 0.019116460 -0.001173916 -0.000588006 -0.000290494
R> plot(x, y, type='b', main="Illustration of convergence towards zero", log="x")
R> abline(h=0, col="grey", lty="dotted")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
859 次 |
最近记录: |