如何在R中寻求目标

时间:2016-02-03 15:50:31

标签: r optimization

我试图在R中写一个函数来确定两个已知半径(r0和r1)和给定重叠区域的圆之间的距离。

我首先写了一个函数来确定重叠区域。

overlap <- function(x0=0, y0=0, r0, x1, y1=0, r1) {
    #plot two circles and calculate the area of overlap
    #doesn't work if one circle completely overlaps the other!

    library("plotrix", lib.loc="~/R/win-library/3.2")

    xmin = min(x0 - r0, x1 - r1)
    xmax = max(x0 + r0, x1 + r1)
    ymin = min(y0 - r0, y1 - r1)
    ymax = max(y0 + r0, y1 + r1)
    plot(c(x0,x1), c(y0,y1), xlim=c(xmin, xmax), ylim=c(ymin, ymax), asp=1)
    draw.circle(x=x0, y=y0, radius=r0)
    draw.circle(x=x1, y=y1, radius=r1)

    d = sqrt((x1-x0)^2 + (y1-y0)^2)  #distance between centroids
    CBA = acos((r1^2 + d^2 - r0^2)/(2*r1*d))
    CBD = 2 * CBA
    CAB = acos((r0^2 + d^2 - r1^2)/(2*r0*d))
    CAD = 2 * CAB
    area = .5 * (r1^2 * (CBD - sin(CBD)) + r0^2 * (CAD - sin(CAD)))
    return(area)
}

我想编写另一个包含重叠函数的函数,并将3个区域作为输入。

dist_between <- function(a_not_b, b_not_a, a_and_b) {

    r0 <- sqrt((a_not_b + a_and_b)/pi)
    r1 <- sqrt((b_not_a + a_and_b)/pi)

    #minimize a_and_b - overlap(r0=r0, x1=?, r1=r1) by changing x1
    return(x1)
}

我希望能够输入类似dist_between(60, 30, 10)的内容并让函数返回值5.805。

我认为optim功能符合我的需要,但我不确定如何开始。

1 个答案:

答案 0 :(得分:1)

这是近似x1解决方案所需的代码行。

x1 <- optimize(function(x) abs(overlap(r0=r0, x1=x, r1=r1)-a_and_b), interval=c(0,r0+r1))