Reputation: 131
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?
Upvotes: 2
Views: 2797
Reputation: 23099
You have x < 0
and y/x = -1.036811 < 0
. Now, it means theta can only be in 2nd or 4th quadrant.
Let tan(-z)=-tan(z)=tan(2*pi-z)=tan(pi-z)=w
, then -z
, pi-z
, 2*pi-z
all equals atan(w)
, the solution is not unique in z
.
atan(y/x)
#[1] -0.8034692
-0.8034692 is a solution means
pi+atan(y/x)
#[1] 2.338123
and
2*pi+atan(y/x)
#[1] 5.479716
are solutions as well.
c(tan(atan(y/x)), tan(pi+atan(y/x)), tan(2*pi+atan(y/x)))
# [1] -1.036811 -1.036811 -1.036811
If we are interested to find solution 0<theta<pi
then the only candidate solution is pi+atan(y/x)=2.338123
Upvotes: 2
Reputation: 32548
It's better to use atan2
atan2(y, x)
#[1] 2.338364
which is (almost) equal to theta
Upvotes: 1