圆内点相对于中心的距离

问题描述 投票:0回答:2

我在计算圆中点相对于R中圆心的距离时遇到一些困难。用我的函数计算出均匀分布点的距离后(请参见下面的完整示例),然后将基于距离截止的数据。绘制时,结果可能不是一个直觉的均匀环。相反,结果是形状奇怪的对象“几乎”是一个环,但沿水平轴被挤压。

我可能在这里遗漏了一些确实很明显的东西,但我无法理解可能是什么。

library(dplyr)

set.seed(111)

# Generate a set of angles from a uniform distribution
theta <- runif(2500, 0, 2 * pi)

# Generate a set of radii from a uniform distribution 
radius <- sqrt(runif(2500))

# Assemble into a matrix of 2D coordinates
x <- radius * cos(theta)
y <- radius * sin(theta)
z <- cbind(x, y)

par(pty = "s") # square plot region
plot.diameter <- c(-1, 1) # plot boundaries
plot(z, pch = 20, cex = 0.20,
     col = rgb(red = 0, green = 0, blue = 0, alpha = 0.5),
     xlim = plot.diameter, ylim = plot.diameter)

enter image description here

# Radial distance function
# Computes the distance of all points within the circle to the circle center 
# Default center: (0, 0)
rad.dist <- function(m, x.center = 0, y.center = 0) {
  (m[, 1] - x.center) ^ 2 + (m[, 2] - y.center) ^ 2 %>%
    sqrt() -> d
  return(d)
}

z.radial <- rad.dist(z)

# Bind radial distance column to coordinates
z <- cbind(z[, 1], z[, 2], z.radial)

# Rename columns for convenience
colnames(z) <- c("x", "y", "rd")

# Subset based on radial distance
outer.ring <- subset(z, z[, 3] >= 0.75)

plot(outer.ring, pch = 20, cex = 0.20,
     col = rgb(red = 0, green = 0, blue = 0, alpha = 0.5),
     xlim = plot.diameter, ylim = plot.diameter)

enter image description here

r geometry coordinates distance
2个回答
2
投票

rad.dist()中的操作顺序是主要问题。特别是magrittr管道的内容使您陷入循环。 1 + 2 %>% sqrt(1 + 2) %>% sqrt


1
投票

这是因为您的点在圆中分布不均匀。


1
投票

%>%具有比+高的优先级。在管道和x^2 + y^2之前,您需要在sqrt周围加上括号。

© www.soinside.com 2019 - 2024. All rights reserved.