将 x 和 y 转换为以弧度为单位的角度
Convert x and y to angle in radians
我使用以下代码创建一个具有随机 rho 和 theta 的点:
set.seed(1)
rho <- sqrt(runif(1, 0.0, 1.0))
theta <- runif(1, 0, 2*pi)
获得rho=0.515
和theta=2.338
我可以通过 -0.358
和 0.371
分别 x=rho*cos(theta)
和 y=rho*sin(theta)
获得 x 和 y 值
但是,如果我执行逆过程
r<-sqrt(x^2+y^2)
结果与 rho 相同,但执行
a<-atan(y/x)
我得到的结果与 theta 不同。
你能告诉我哪里做错了吗?
最好用atan2
atan2(y, x)
#[1] 2.338364
(几乎)等于 theta
Here is more discussion.
您有 x < 0
和 y/x = -1.036811 < 0
。现在,这意味着 theta 只能在第二或第四象限。
设tan(-z)=-tan(z)=tan(2*pi-z)=tan(pi-z)=w
,则-z
、pi-z
、2*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
我使用以下代码创建一个具有随机 rho 和 theta 的点:
set.seed(1)
rho <- sqrt(runif(1, 0.0, 1.0))
theta <- runif(1, 0, 2*pi)
获得rho=0.515
和theta=2.338
我可以通过 -0.358
和 0.371
分别 x=rho*cos(theta)
和 y=rho*sin(theta)
获得 x 和 y 值
但是,如果我执行逆过程
r<-sqrt(x^2+y^2)
结果与 rho 相同,但执行
a<-atan(y/x)
我得到的结果与 theta 不同。
你能告诉我哪里做错了吗?
最好用atan2
atan2(y, x)
#[1] 2.338364
(几乎)等于 theta
Here is more discussion.
您有 x < 0
和 y/x = -1.036811 < 0
。现在,这意味着 theta 只能在第二或第四象限。
设tan(-z)=-tan(z)=tan(2*pi-z)=tan(pi-z)=w
,则-z
、pi-z
、2*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