在圆上创建随机点

Create random points on a circle

在 R 中带有噪声的特定半径圆上创建随机点的最简单方法是什么?有做这种事情的图书馆吗?

theta = runif(100, 0,2*pi)
x = cos(theta) + rnorm(100, 0, 0.03)
y = sin(theta) + rnorm(100, 0, 0.03)
plot(x,y, pch=20)

采样会更自然:

  • [0, 2*pi)
  • 支持的均匀分布的极角 theta
  • (0, Inf) 支持的对数正态分布的极半径 r,因此 log(r) 服从均值 meanlog 和标准差 sdlog 的正态分布.

所以你可以尝试这样的事情:

set.seed(1L)
n <- 100L
theta <- runif(n, 0, 2 * pi)
r <- rlnorm(n, meanlog = log(2), sdlog = 0.1)
plot(r * cos(theta), r * sin(theta), asp = 1)

您可以像这样推广到多个圈子:

circles <- function(n, mu, sigma) {
    lr <- Map(rlnorm, n = n, meanlog = mu, sdlog = sigma)
    N <- length(lr)
    n <- lengths(lr, FALSE)
    data.frame(group = rep.int(gl(N, 1L), n),
               r = unlist(lr, FALSE, FALSE),
               theta = runif(sum(n), 0, 2 * pi))
}

set.seed(1L)
d <- circles(n = c(25L, 100L, 400L), mu = log(c(1, 2, 4)), sigma = c(0, 0.05, 0.1))
str(d)
## 'data.frame':    525 obs. of  3 variables:
##  $ group: Factor w/ 3 levels "1","2","3": 1 1 1 1 1 1 1 1 1 1 ...
##  $ r    : num  1 1 1 1 1 1 1 1 1 1 ...
##  $ theta: num  3.335 4.303 2.408 6 0.744 ...

par(mfrow = c(1L, 2L))
with(d, {
    plot(r * cos(theta), r * sin(theta), asp = 1, col = group)
    plot(r * cos(theta), r * sin(theta), asp = 1, col = cut(theta, 0:3 * 2 * pi / 3))
})

函数circlesnmusigma中被向量化,其中n是圆中的点数,musigma 是对数半径的平均值和标准偏差。

我们可以使用1i构造极坐标(complex格式)然后plot

set.seed(1)
n <- 100
plot(rnorm(n, 1, 0.1) * exp(1i * runif(n, 0, 2 * pi)))