繁体   English   中英

如何在r中得到n的向量作为box muller function的output

[英]How to get a vector of n as the output of box muller function in r

我写了一个 box muller function。但是,我的 output 的长度是 2n。 如何让我的 output 成为长度为 n 的向量?

您的 function 需要返回两个向量的列表,每个向量的长度为n 调用这些xy是明智的:

box_muller <- function(n) {
  U1 <- runif(n)
  U2 <- runif(n)
  X1 <- sqrt(-2*log(U1))*cos(2*pi*U2)
  X2 <- sqrt(-2*log(U1))*sin(2*pi*U2)
  return(list(x = X1, y = X2))
}

现在对其进行测试,我们可以创建一个包含xy分量的列表,每个分量都应该独立于标准正态分布:

set.seed(1)

n = 1000

BM <- box_muller(n)

我们可以直接拨打plot object:

plot(BM)

并确认其成员的长度

length(BM$x)
#> [1] 1000
length(BM$y)
#> [1] 1000

plot 是整个 object 的直方图没有意义,但我们可以为它的每个成员绘制一个

hist(BM$x)


hist(BM$y)

我们可以确认xy不相关

cor(BM$x, BM$y)
#> [1] -0.01615875

创建于 2022-09-29,使用reprex v2.0.2

暂无
暂无

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

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