2

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?

d.b
  • 32,245
  • 6
  • 36
  • 77
R user
  • 131
  • 3
  • 14
  • The function tangens has a period of `pi`. So you must inspect the signs of `x` and `y` to find out the quadrant of the point. It is a mathematical (resp. logical) problem. – jogo Mar 01 '17 at 19:17
  • You mean to check if they are positive or negative? How to do it in those cases? – R user Mar 01 '17 at 19:20

2 Answers2

2

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

Sandipan Dey
  • 21,482
  • 2
  • 51
  • 63
1

It's better to use atan2

atan2(y, x)
#[1] 2.338364

which is (almost) equal to theta

Here is more discussion.

Community
  • 1
  • 1
d.b
  • 32,245
  • 6
  • 36
  • 77