将x和y转换为弧度角度

时间:2017-03-01 19:13:40

标签: r coordinates trigonometry angle points

我用随机rho和theta创建一个带有以下代码的点:

set.seed(1)
rho <- sqrt(runif(1, 0.0, 1.0))
theta <- runif(1, 0, 2*pi)

获取rho=0.515theta=2.338

我可以分别使用x=rho*cos(theta)y=rho*sin(theta)获取-0.3580.371的x和y值

但是,如果我正在进行逆程序

   r<-sqrt(x^2+y^2)

其结果与rho相同但正在进行

   a<-atan(y/x)

我获得的结果与theta不同。

你能说出我做错了什么吗?

2 个答案:

答案 0 :(得分:2)

您有x < 0y/x = -1.036811 < 0。现在,这意味着theta只能在第二或第四象限。

tan(-z)=-tan(z)=tan(2*pi-z)=tan(pi-z)=w,然后-zpi-z2*pi-z等于atan(w),解决方案在z中不是唯一的。

atan(y/x)
#[1] -0.8034692 

-0.8034692是解决方案

pi+atan(y/x)
#[1] 2.338123

2*pi+atan(y/x)
#[1] 5.479716

也是解决方案。

c(tan(atan(y/x)), tan(pi+atan(y/x)), tan(2*pi+atan(y/x)))
# [1] -1.036811 -1.036811 -1.036811

如果我们有兴趣找到解决方案0<theta<pi,那么唯一的候选解决方案是pi+atan(y/x)=2.338123

答案 1 :(得分:1)

最好使用atan2

atan2(y, x)
#[1] 2.338364

(几乎)等于theta

Here is more discussion.