想象一下,我们有一个由以下定义的圆圈:
X^2 + Y^2 = r^2
圆的原点是0
和radius = 1
。如果我们从原点画一条水平线向右移动坐标(x1,y1)=(0,0)
,(x2,y2) = (2,0)
这条线应该与圆相交。例如
library(plotrix)
plot(0,0,xlim=c(-3,3),ylim=c(-2,2))
draw.circle(0,0,1)
lines(c(0,2),c(0,0))
我试图找到线与圆的交点,但没有运气。我从this wolfram page中采用了我的方法并生成了以下代码,但它似乎没有产生正确的结果。有人可以指出我的(毫无疑问)愚蠢的错误吗?
r <- 1
id <- 1:5
x1 <- c(0)
y1 <- c(0)
x2 <- c(2)
y2 <- c(0)
df <- data.frame(id,x1,y1,x2,y2)
df <- transform(df, dx = x2-x1)
df <- transform(df, dy = y2-y1)
df <- transform(df, dr = sqrt(dx^2+dy^2))
df <- transform(df, D = (x1*y2)-(x2*y1))
df <- transform(df, dysign = sapply(dy,function(x) ifelse(x < 0,-1,1)))
df <- transform(df, newxplus = (D*dy + (dysign*dy) *dx*sqrt(r^2*dr^2-D^2))/dr^2)
df <- transform(df, newxneg = (D*dy - (dysign*dy) *dx*sqrt(r^2*dr^2-D^2))/dr^2)
df <- transform(df, newyplus = (-D*dx + (abs(dy)) *sqrt(r^2*dr^2-D^2))/dr^2)
df <- transform(df, newyneg = (-D*dx - (abs(dy)) *sqrt(r^2*dr^2-D^2))/dr^2)
# where newxplus and newxneg are the two x coordinates for the two possible intercepts
# similarly for newyplus and newyneg
df