R user R user -4 years ago 175
R Question

Convert x and y to angle in radians

I create a point with a random rho and theta with the following code:

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


obtaining
rho=0.515
and
theta=2.338


I can get the x and y values doing
x=rho*cos(theta)
and
y=rho*sin(theta)
with
-0.358
and
0.371
, respectively

However, if I'm doing the inverse procedure

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


which results the same as rho but doing

a<-atan(y/x)


I obtain a different result than theta.

Could you tell what I'm doing wrong?

Answer Source

It's better to use atan2

atan2(y, x)
#[1] 2.338364

which is (almost) equal to theta

Here is more discussion.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download