# Algorithms: x,y values convert to angle.

• Feb 21st 2013, 01:08 AM
JeffreyR
Algorithms: x,y values convert to angle.
Hi i am new on the forum. I am making a smartphone application and this
is the first time i’m working with algorithms.

I am looking for algorithms that can convert x and y value on a Cartesian plane (x,y) to a angle. The angle can be 0-360 degrees or 0-2π radians.

Does anyoneknow of such algorithms?

I have looked for geometric algorithms on Google. I have also found a list ofalgorithms on Wikipedia, but no luck finding this particular algorithm.

Also are there search databases that solely contain algorithms?

Below is a visual presentation of the conversion the algorithm has to do:

http://i50.tinypic.com/34g6g3m.jpg

• Feb 21st 2013, 07:20 AM
HallsofIvy
Re: Algorithms: x,y values convert to angle.
Convert the point (x, y) to what angle? Do you mean the angle the line through (0, 0) and (x, y) makes with the x-axis? That appears to be what your pictures show. If so then you need to look at the right triangle which has vertices at (0, 0), (x, y), and (x, 0). That has its right angle at (x, 0) and has $tan(\theta)= y/x$ so that $\theta= arctan(y/x)= tan^{-1}(y/x)$. One complication is that, since the tangent function is NOT one to one, the arctangent is defined only for $-\pi/2\le \theta\le \pi/2$. So, if you want $\theta$ from 0 to 360 degrees, you will need an algorithm like

If x= 0, if y>0 $\theta= 90$ else $\theta= 270$ (to avoid dividing by 0)
else, A= arctan(y/x) {If If A>0 and then $\theta= A$ else $\theta= 360+ A$}
else ( $x\le 0$ now) if A> 0, $\theta= 90+ A$ else $\theta= 270- A$
• Feb 21st 2013, 08:24 PM
johng
Re: Algorithms: x,y values convert to angle.
Here's psuedo code for an algorithm that I have used successfully. It assumes the existence of an arccos function that returns a value in [0,pi]

double angle(x,y)
d=x*x+y*y
if (d is 0) return error
d=sqrt(d)
v=arccos(x/d)
if (y<0) v=2*pi-v
return v