如何在给定指定区域的情况下生成随机形状.(R语言).

Pra*_*eep 2 2d r area shapes

我的问题是这个..我正在研究一些聚类算法..为此我首先尝试了2d形状..

鉴于特定区域说500sq单位..我需要为特定区域生成随机形状

说一个500平方米的矩形,正方形,三角形等等..有关我应该如何解决这个问题的任何建议..我正在使用R语言..

nic*_*ico 6

对常规多边形执行此操作非常简单.

具有半径为R的外接圆的n边正多边形的面积为

A = 1/2 nR^2 * sin((2pi)/n)

因此,知道n和A你就可以轻松找到R.

R = sqrt((2*A)/(n*sin((2pi)/n))

因此,您可以选择中心,距离R并以2pi/n角度增量生成n个点.

在R:

regular.poly <- function(nSides, area)
    {
    # Find the radius of the circumscribed circle
    radius <- sqrt((2*area)/(nSides*sin((2*pi)/nSides)))

    # I assume the center is at (0;0) and the first point lies at (0; radius)
    points <- list(x=NULL, y=NULL)
    angles <- (2*pi)/nSides * 1:nSides

    points$x <- cos(angles) * radius
    points$y <- sin(angles) * radius

    return (points);
    }


# Some examples
par(mfrow=c(3,3))

for (i in 3:11)
    {
    p <- regular.poly(i, 100)
    plot(0, 0, "n", xlim=c(-10, 10), ylim=c(-10, 10), xlab="", ylab="", main=paste("n=", i))
    polygon(p)
    }
Run Code Online (Sandbox Code Playgroud)

我们可以推断出一般的凸多边形.

凸多边形的区域可以是: A = 1/2 * [(x1*y2 + x2*y3 + ... + xn*y1) - (y1*x2 + y2*x3 + ... + yn*x1)]

我们如上所述生成多边形,但偏离正多边形的角度和半径.

然后我们缩放点以获得所需的区域.

convex.poly <- function(nSides, area)
    {
    # Find the radius of the circumscribed circle, and the angle of each point if this was a regular polygon
    radius <- sqrt((2*area)/(nSides*sin((2*pi)/nSides)))
    angle <- (2*pi)/nSides

    # Randomize the radii/angles
    radii <- rnorm(nSides, radius, radius/10)
    angles <- rnorm(nSides, angle, angle/10) * 1:nSides
    angles <- sort(angles)

    points <- list(x=NULL, y=NULL)
    points$x <- cos(angles) * radii
    points$y <- sin(angles) * radii

    # Find the area of the polygon
    m <- matrix(unlist(points), ncol=2)
    m <- rbind(m, m[1,])
    current.area <- 0.5 * (sum(m[1:nSides,1]*m[2:(nSides+1),2]) - sum(m[1:nSides,2]*m[2:(nSides+1),1]))

    points$x <- points$x * sqrt(area/current.area)
    points$y <- points$y * sqrt(area/current.area)

    return (points)
    }
Run Code Online (Sandbox Code Playgroud)