圆内点相对于中心的距离

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

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

library(dplyr)

set.seed(111)

# Generate a set of angles from a uniform distribution
theta <- runif(2500,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)

圆内点相对于中心的距离

# 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,3] >= 0.75)

plot(outer.ring,ylim = plot.diameter)

圆内点相对于中心的距离

chenglong678 回答:圆内点相对于中心的距离

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

rad.dist <- function(m,x.center = 0,y.center = 0) {
  sqrt((m[,1] - x.center)^2 + (m[,2] - y.center)^2)
}

outer.ring <- z[rad.dist(z) >= 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)
,

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

要在圆形(通常是球体)中生成均匀点,可以使用uniformly包:

library(uniformly)

npoints <- 2500
z <- runif_in_sphere(npoints,d = 2,r = 1)

rad.dist <- function(m,1] - x.center) ^ 2 + (m[,2] - y.center) ^ 2)
}
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,3] >= 0.75)
# plot
par(pty = "s")
plot(outer.ring,xlim = c(-1,1),ylim = c(-1,1))

enter image description here

如果您的目标是在环空中获得均匀的点,则可以直接使用uniformly生成它们:

z <- runif_in_annulus(1000,c(0,0),0.75,1)
plot(z,1))
,

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

> library(magrittr)     # or dplyr,or anywhere it's reexported
> 2+2 %>% sqrt()
[1] 3.414214
> (2+2) %>% sqrt()
[1] 2
> 2 + (2 %>% sqrt())
[1] 3.414214
本文链接:https://www.f2er.com/3131165.html

大家都在问