[英]how to goal seek in R
I am attempting to write a function in R to determine the distance between two circles with known radii (r0 and r1) and a given area of overlap. 我试图在R中编写一个函数,以确定半径已知(r0和r1)且给定重叠区域的两个圆之间的距离。
I first wrote a function to determine the area of overlap. 我首先编写了一个函数来确定重叠区域。
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)
}
I want to write another function that includes the overlap function and takes 3 areas as input. 我想编写另一个函数,其中包括重叠函数,并以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)
}
I want to be able to enter something like dist_between(60, 30, 10)
and have the function return the value 5.805. 我希望能够输入dist_between(60, 30, 10)
东西dist_between(60, 30, 10)
并让该函数返回值5.805。
I think the optim
function would suit my needs but I'm not sure how to begin. 我认为optim
功能可以满足我的需求,但是我不确定如何开始。
这是近似于x1解决方案所需的代码行。
x1 <- optimize(function(x) abs(overlap(r0=r0, x1=x, r1=r1)-a_and_b), interval=c(0,r0+r1))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.